<?php
/**
* Contains most functions used by the main calendar, task list and control panel (excluding mobile versions).
*/
if(defined("IZ_ACCNAME")) {
mt_srand((double)microtime()*1000000);
$utcoffset = date('Z',time()); // offset in seconds
/**
* Establishes a cpnnection to the database.
*/
function izsql() {
    global $dbhost;
    global $dbuser;
    global $dbpass;
    global $dbdatabase;
    global $sqlver;
    if(IZ_CALMODE == 'mysql') {
      if($_SESSION['MYSQLi']) {
        global $dblink;
        $dblink = mysqli_connect($dbhost,$dbuser,$dbpass,$dbdatabase);
        if(mysqli_connect_errno()) {
           echo 'Can\'t connect to MySQL Server as user: ',$dbuser,',Errorcode: ',mysqli_connect_error(),"\n";
           die();
        }
      } else {
        $dblink = mysql_connect($dbhost,$dbuser,$dbpass);
        mysql_select_db($dbdatabase,$dblink) or die('&#35;44&#58; '.ERR_DBCONNECTFAIL.'&#58; '.mysql_error());
        if(version_compare((string)$sqlver,"4.1",">=")) {
          @mysql_query("SET NAMES 'utf8'");
        }
      }
    } elseif(IZ_CALMODE == 'postgre') {
      return pg_connect("host=$dbhost dbname=$dbdatabase user=$dbuser password=$dbpass");
    } elseif(IZ_CALMODE == 'msq') {
      $dblink = mssql_connect($dbhost, $dbuser, $dbpass);
      mssql_select_db($dbdatabase, $dblink) or die('&#35;44&#58; '.ERR_DBCONNECTFAIL.'&#58; '.mssql_get_last_message());
    }
}
/**
* Removes line breaks and <br>s
* @param par The text to format.
*/
function nobreaks($par) {
         $trans = array("\r\n" => '',
                       "\n\r" => '',
                       "\n" => '',
                       "\r" => '',
                       "<br>" => '',
                       "<br />" => ''
                  );
         $cleaned = strtr($par,$trans);
         return $cleaned;
}
/**
* Converts the input of the attendees field and converts line breaks to commas and encodes double quotes
* so everything is in a standard format.
* @param par The text to format
*/
function input2attendees($par) {
         $trans = array("\r\n" => ',',
                       "\n\r" => ',',
                       "\n" => ',',
                       "\r" => ',',
                       '<br>' => ',',
                       '<br />' => ',',
                       '"' => '&#34;',
                       ' ' => '',
                       ',,' => ',',
//                       ',' => ','
                  );
         $cleaned = strtr($par,$trans); // remove double commas and add spaces
         return $cleaned;
}
/**
* Converts line breaks to <br>s and unencodes ampersands
* @param value The text to format.
*/
function xmlUnescapeDbEscape($value) {
      $trans = array(
                     "\r\n" => '<br />',
                     "\n\r" => '<br />',
                     "\n" => '<br />',
                     "\r" => '<br />',
                     "'" => "\'",
                     '&amp;' => '&',
               );
    return strtr(trim($value),$trans);
}
/**
* Unescapes quotes and apersands
* @param value The text to format.
*/
function xmlUnescapeDbEscapeHTML($value) {
      $trans = array(
                     "'" => "\'",
                     '&amp;' => '&',
               );
    return strtr(trim($value),$trans);
}
/**
* Sanitises input by converting line breaks to <br>s and encodes characters to entities
* @param par The text to format.
*/
function clean($par) {
         $entities = get_html_translation_table(HTML_SPECIALCHARS);
         $extra = array("\r\n" => '<br />',
                       "\n\r" => '<br />',
                       "\n" => '<br />',
                       "\r" => '<br />',
                       "__NL__" => '<br />',
                       "__SPC__" => ' ',

                       "Á"   =>   '&#193;',       //latin capital letter A with acute
                       "á"   =>   '&#225;',       //latin small letter a with acute
                       "Â"   =>   '&#194;',       //latin capital letter A with circumflex
                       "â"   =>   '&#226;',       //latin small letter a with circumflex
                       "Æ"   =>   '&#198;',       //latin capital letter AE = latin capital ligature AE
                       "æ"   =>   '&#230;',       //latin small letter ae = latin small ligature ae
                       "À"   =>   '&#192;',       //latin capital letter A with grave = latin capital letter A grave
                       "à"   =>   '&#224;',       //latin small letter a with grave = latin small letter a grave
                       "Å"   =>   '&#197;',       //latin capital letter A with ring above = latin capital letter A ring
                       "å"   =>   '&#229;',       //latin small letter a with ring above = latin small letter a ring
                       "Ã"   =>   '&#195;',       //latin capital letter A with tilde
                       "ã"   =>   '&#227;',       //latin small letter a with tilde
                       "Ä"   =>   '&#196;',       //latin capital letter A with diaeresis
                       "ä"   =>   '&#228;',       //latin small letter a with diaeresis
                       "Ç"   =>   '&#199;',       //latin capital letter C with cedilla
                       "ç"   =>   '&#231;',       //latin small letter c with cedilla
                       "É"   =>   '&#201;',       //latin capital letter E with acute
                       "é"   =>   '&#233;',       //latin small letter e with acute
                       "Ê"   =>   '&#202;',       //latin capital letter E with circumflex
                       "ê"   =>   '&#234;',       //latin small letter e with circumflex
                       "È"   =>   '&#200;',       //latin capital letter E with grave
                       "è"   =>   '&#232;',       //latin small letter e with grave
                       "Ð"   =>   '&#208;',       //latin capital letter ETH
                       "ð"   =>   '&#240;',       //latin small letter eth
                       "Ë"   =>   '&#203;',       //latin capital letter E with diaeresis
                       "ë"   =>   '&#235;',       //latin small letter e with diaeresis
                       "Í"   =>   '&#205;',       //latin capital letter I with acute
                       "í"   =>   '&#237;',       //latin small letter i with acute
                       "Î"   =>   '&#206;',       //latin capital letter I with circumflex
                       "î"   =>   '&#238;',       //latin small letter i with circumflex
                       "Ì"   =>   '&#204;',       //latin capital letter I with grave
                       "ì"   =>   '&#236;',       //latin small letter i with grave
                       "Ï"   =>   '&#207;',       //latin capital letter I with diaeresis
                       "ï"   =>   '&#239;',       //latin small letter i with diaeresis
                       "Ñ"   =>   '&#209;',       //latin capital letter N with tilde
                       "ñ"   =>   '&#241;',       //latin small letter n with tilde
                       "Ó"   =>   '&#211;',       //latin capital letter O with acute
                       "ó"   =>   '&#243;',       //latin small letter o with acute
                       "Ô"   =>   '&#212;',       //latin capital letter O with circumflex
                       "ô"   =>   '&#244;',       //latin small letter o with circumflex
                       "Œ"   =>   '&#338;',       //latin capital ligature OE
                       "œ"   =>   '&#339;',       //latin small ligature oe (note)
                       "Ò"   =>   '&#210;',       //latin capital letter O with grave
                       "ò"   =>   '&#242;',       //latin small letter o with grave
                       "Ø"   =>   '&#216;',       //latin capital letter O with stroke = latin capital letter O slash
                       "ø"   =>   '&#248;',       //latin small letter o with stroke, = latin small letter o slash
                       "Õ"   =>   '&#213;',       //latin capital letter O with tilde
                       "õ"   =>   '&#245;',       //latin small letter o with tilde
                       "Ö"   =>   '&#214;',       //latin capital letter O with diaeresis
                       "ö"   =>   '&#246;',       //latin small letter o with diaeresis
                       "Š"   =>   '&#352;',       //latin capital letter S with caron
                       "š"   =>   '&#353;',       //latin small letter s with caron
                       "ß"   =>   '&#223;',       //latin small letter sharp s = ess-zed
                       "Þ"   =>   '&#222;',       //latin capital letter THORN
                       "þ"   =>   '&#254;',       //latin small letter thorn
                       "Ú"   =>   '&#218;',       //latin capital letter U with acute
                       "ú"   =>   '&#250;',       //latin small letter u with acute
                       "Û"   =>   '&#219;',       //latin capital letter U with circumflex
                       "û"   =>   '&#251;',       //latin small letter u with circumflex
                       "Ù"   =>   '&#217;',       //latin capital letter U with grave
                       "ù"   =>   '&#249;',       //latin small letter u with grave
                       "Ü"   =>   '&#220;',       //latin capital letter U with diaeresis
                       "ü"   =>   '&#252;',       //latin small letter u with diaeresis
                       "Ý"   =>   '&#221;',       //latin capital letter Y with acute
                       "ý"   =>   '&#253;',       //latin small letter y with acute
                       "ÿ"   =>   '&#255;',       //latin small letter y with diaeresis
                       "Ÿ"   =>   '&#376;',       //latin capital letter Y with diaeresis
              
                       "&" => '&amp;',     //ampersand  
                       ':' => '&#58;',
                       ';' => '&#59;',
         //              "'" => '&#39;',
                       '(' => '&#40;',
                       ')' => '&#41;',
                       '£' => '&#163;', // pound sterling
                       '¥' => '&#165;', // yen
                       
                       // Problematic with mysql - replace just incase
                       'Č' => '&#268;',
                       'č' => '&#269;',
                       'ž' => '&#382;',
                  );
         return strtr($par,$entities);
}
/**
* Sanitises input by converting line breaks to <br>s and encodes characters to entities
* Also strips disallowed HTML tags.
* @param par The text to format.
*/
function htmlclean($par) {
         // converts input to sanitised HTML
         $entities = array("__NL__" => '<br />',
                       "__SPC__" => ' ',

                       "Á"   =>   '&#193;',       //latin capital letter A with acute
                       "á"   =>   '&#225;',       //latin small letter a with acute
                       "Â"   =>   '&#194;',       //latin capital letter A with circumflex
                       "â"   =>   '&#226;',       //latin small letter a with circumflex
                       "Æ"   =>   '&#198;',       //latin capital letter AE = latin capital ligature AE
                       "æ"   =>   '&#230;',       //latin small letter ae = latin small ligature ae
                       "À"   =>   '&#192;',       //latin capital letter A with grave = latin capital letter A grave
                       "à"   =>   '&#224;',       //latin small letter a with grave = latin small letter a grave
                       "Å"   =>   '&#197;',       //latin capital letter A with ring above = latin capital letter A ring
                       "å"   =>   '&#229;',       //latin small letter a with ring above = latin small letter a ring
                       "Ã"   =>   '&#195;',       //latin capital letter A with tilde
                       "ã"   =>   '&#227;',       //latin small letter a with tilde
                       "Ä"   =>   '&#196;',       //latin capital letter A with diaeresis
                       "ä"   =>   '&#228;',       //latin small letter a with diaeresis
                       "Ç"   =>   '&#199;',       //latin capital letter C with cedilla
                       "ç"   =>   '&#231;',       //latin small letter c with cedilla
                       "É"   =>   '&#201;',       //latin capital letter E with acute
                       "é"   =>   '&#233;',       //latin small letter e with acute
                       "Ê"   =>   '&#202;',       //latin capital letter E with circumflex
                       "ê"   =>   '&#234;',       //latin small letter e with circumflex
                       "È"   =>   '&#200;',       //latin capital letter E with grave
                       "è"   =>   '&#232;',       //latin small letter e with grave
                       "Ð"   =>   '&#208;',       //latin capital letter ETH
                       "ð"   =>   '&#240;',       //latin small letter eth
                       "Ë"   =>   '&#203;',       //latin capital letter E with diaeresis
                       "ë"   =>   '&#235;',       //latin small letter e with diaeresis
                       "Í"   =>   '&#205;',       //latin capital letter I with acute
                       "í"   =>   '&#237;',       //latin small letter i with acute
                       "Î"   =>   '&#206;',       //latin capital letter I with circumflex
                       "î"   =>   '&#238;',       //latin small letter i with circumflex
                       "Ì"   =>   '&#204;',       //latin capital letter I with grave
                       "ì"   =>   '&#236;',       //latin small letter i with grave
                       "Ï"   =>   '&#207;',       //latin capital letter I with diaeresis
                       "ï"   =>   '&#239;',       //latin small letter i with diaeresis
                       "Ñ"   =>   '&#209;',       //latin capital letter N with tilde
                       "ñ"   =>   '&#241;',       //latin small letter n with tilde
                       "Ó"   =>   '&#211;',       //latin capital letter O with acute
                       "ó"   =>   '&#243;',       //latin small letter o with acute
                       "Ô"   =>   '&#212;',       //latin capital letter O with circumflex
                       "ô"   =>   '&#244;',       //latin small letter o with circumflex
                       "Œ"   =>   '&#338;',       //latin capital ligature OE
                       "œ"   =>   '&#339;',       //latin small ligature oe (note)
                       "Ò"   =>   '&#210;',       //latin capital letter O with grave
                       "ò"   =>   '&#242;',       //latin small letter o with grave
                       "Ø"   =>   '&#216;',       //latin capital letter O with stroke = latin capital letter O slash
                       "ø"   =>   '&#248;',       //latin small letter o with stroke, = latin small letter o slash
                       "Õ"   =>   '&#213;',       //latin capital letter O with tilde
                       "õ"   =>   '&#245;',       //latin small letter o with tilde
                       "Ö"   =>   '&#214;',       //latin capital letter O with diaeresis
                       "ö"   =>   '&#246;',       //latin small letter o with diaeresis
                       "Š"   =>   '&#352;',       //latin capital letter S with caron
                       "š"   =>   '&#353;',       //latin small letter s with caron
                       "ß"   =>   '&#223;',       //latin small letter sharp s = ess-zed
                       "Þ"   =>   '&#222;',       //latin capital letter THORN
                       "þ"   =>   '&#254;',       //latin small letter thorn
                       "Ú"   =>   '&#218;',       //latin capital letter U with acute
                       "ú"   =>   '&#250;',       //latin small letter u with acute
                       "Û"   =>   '&#219;',       //latin capital letter U with circumflex
                       "û"   =>   '&#251;',       //latin small letter u with circumflex
                       "Ù"   =>   '&#217;',       //latin capital letter U with grave
                       "ù"   =>   '&#249;',       //latin small letter u with grave
                       "Ü"   =>   '&#220;',       //latin capital letter U with diaeresis
                       "ü"   =>   '&#252;',       //latin small letter u with diaeresis
                       "Ý"   =>   '&#221;',       //latin capital letter Y with acute
                       "ý"   =>   '&#253;',       //latin small letter y with acute
                       "ÿ"   =>   '&#255;',       //latin small letter y with diaeresis
                       "Ÿ"   =>   '&#376;',       //latin capital letter Y with diaeresis
              
                       '(' => '&#40;',
                       ')' => '&#41;',
                       '£' => '&#163;', // pound sterling
                       '¥' => '&#165;', // yen
                       
                       // Problematic with mysql - replace just incase
                       'Č' => '&#268;',
                       'č' => '&#269;',
                       'ž' => '&#382;',
                  );
         $cleaned = strip_tags(strtr($par,$entities),'<p><a><li><ol><ul><br><span><em><strong><u><img>)');
         return $cleaned;
}
/**
* Converts entities to UTF8 characters and re-inserts CRLFs.
* @param par The text to format.
*/
function dirty($par) {
         $entities = get_html_translation_table(HTML_SPECIALCHARS);
         $extra = array("<br />" => "\n",
                        '&#193;'   =>   "Á",       //latin capital letter A with acute
                        '&#225;'   =>   "á",       //latin small letter a with acute
                        '&#194;'   =>   "Â",       //latin capital letter A with circumflex
                        '&#226;'   =>   "â",       //latin small letter a with circumflex
                        '&#198;'   =>   "Æ",       //latin capital letter AE = latin capital ligature AE
                        '&#230;'   =>   "æ",       //latin small letter ae = latin small ligature ae
                        '&#192;'   =>   "À",       //latin capital letter A with grave = latin capital letter A grave
                        '&#224;'   =>   "à",       //latin small letter a with grave = latin small letter a grave
                        '&#197;'   =>   "Å",       //latin capital letter A with ring above = latin capital letter A ring
                        '&#229;'   =>   "å",       //latin small letter a with ring above = latin small letter a ring
                        '&#195;'   =>   "Ã",       //latin capital letter A with tilde
                        '&#227;'   =>   "ã",       //latin small letter a with tilde
                        '&#196;'   =>   "Ä",       //latin capital letter A with diaeresis
                        '&#228;'   =>   "ä",       //latin small letter a with diaeresis
                        '&#199;'   =>   "Ç",       //latin capital letter C with cedilla
                        '&#231;'   =>   "ç",       //latin small letter c with cedilla
                        '&#201;'   =>   "É",       //latin capital letter E with acute
                        '&#233;'   =>   "é",       //latin small letter e with acute
                        '&#202;'   =>   "Ê",       //latin capital letter E with circumflex
                        '&#234;'   =>   "ê",       //latin small letter e with circumflex
                        '&#200;'   =>   "È",       //latin capital letter E with grave
                        '&#232;'   =>   "è",       //latin small letter e with grave
                        '&#208;'   =>   "Ð",       //latin capital letter ETH
                        '&#240;'   =>   "ð",       //latin small letter eth
                        '&#203;'   =>   "Ë",       //latin capital letter E with diaeresis
                        '&#235;'   =>   "ë",       //latin small letter e with diaeresis
                        '&#205;'   =>   "Í",       //latin capital letter I with acute
                        '&#237;'   =>   "í",       //latin small letter i with acute
                        '&#206;'   =>   "Î",       //latin capital letter I with circumflex
                        '&#238;'   =>   "î",       //latin small letter i with circumflex
                        '&#204;'   =>   "Ì",       //latin capital letter I with grave
                        '&#236;'   =>   "ì",       //latin small letter i with grave
                        '&#207;'   =>   "Ï",       //latin capital letter I with diaeresis
                        '&#239;'   =>   "ï",       //latin small letter i with diaeresis
                        '&#209;'   =>   "Ñ",       //latin capital letter N with tilde
                        '&#241;'   =>   "ñ",       //latin small letter n with tilde
                        '&#211;'   =>   "Ó",       //latin capital letter O with acute
                        '&#243;'   =>   "ó",       //latin small letter o with acute
                        '&#212;'   =>   "Ô",       //latin capital letter O with circumflex
                        '&#244;'   =>   "ô",       //latin small letter o with circumflex
                        '&#338;'   =>   "Œ",       //latin capital ligature OE
                        '&#339;'   =>   "œ",       //latin small ligature oe (note)
                        '&#210;'   =>   "Ò",       //latin capital letter O with grave
                        '&#242;'   =>   "ò",       //latin small letter o with grave
                        '&#216;'   =>   "Ø",       //latin capital letter O with stroke = latin capital letter O slash
                        '&#248;'   =>   "ø",       //latin small letter o with stroke, = latin small letter o slash
                        '&#213;'   =>   "Õ",       //latin capital letter O with tilde
                        '&#245;'   =>   "õ",       //latin small letter o with tilde
                        '&#214;'   =>   "Ö",       //latin capital letter O with diaeresis
                        '&#246;'   =>   "ö",       //latin small letter o with diaeresis
                        '&#352;'   =>   "Š",       //latin capital letter S with caron
                        '&#353;'   =>   "š",       //latin small letter s with caron
                        '&#223;'   =>   "ß",       //latin small letter sharp s = ess-zed
                        '&#222;'   =>   "Þ",       //latin capital letter THORN
                        '&#254;'   =>   "þ",       //latin small letter thorn
                        '&#218;'   =>   "Ú",       //latin capital letter U with acute
                        '&#250;'   =>   "ú",       //latin small letter u with acute
                        '&#219;'   =>   "Û",       //latin capital letter U with circumflex
                        '&#251;'   =>   "û",       //latin small letter u with circumflex
                        '&#217;'   =>   "Ù",       //latin capital letter U with grave
                        '&#249;'   =>   "ù",       //latin small letter u with grave
                        '&#220;'   =>   "Ü",       //latin capital letter U with diaeresis
                        '&#252;'   =>   "ü",       //latin small letter u with diaeresis
                        '&#221;'   =>   "Ý",       //latin capital letter Y with acute
                        '&#253;'   =>   "ý",       //latin small letter y with acute
                        '&#255;'   =>   "ÿ",       //latin small letter y with diaeresis
                        '&#376;'   =>   "Ÿ",       //latin capital letter Y with diaeresis
              
               '&amp;'     => "&", //ampersand  
               '&quot;'    => '"', //double quote
               '&#34;'    => '"', //double quote
               '&#58;'     =>  ':',
               '&#59;'     =>  ';',
               '&#39;'     =>  "'",
               '&#40;'     =>  '(',
               '&#41;'     =>  ')',
              
              // Problematic with mysql - replace just incase
               '&#268;'=>  'Č',
               '&#269;'=>  'č',
               '&#382;'=>  'ž',
                  );
         $entities = array_flip($entities);
         $trans = array_merge($entities,$extra);
         $cleaned = strtr($par,$trans);
         return $cleaned;
}
/**
* Returns the contents of a day as HTML.
* @param epochsecs The starting second of the day.
*/
function get_day($epochsecs) {
         global $onload;
         $opt_flags = $_SESSION['IZ_OPT'];
         list($day, $month, $year) = explode(" ",date("j n Y",$epochsecs));
         if($_SESSION['edit'] > 0) {
           $return .= '<a id="mousehookaddday" href="'.$_SESSION['IZ_CALURL'].'index.php?act=add&amp;adddate='.date("d-m-Y",$epochsecs).'" title="'.STR_ADDEVENTON.' '.iz_longdate($epochsecs).'" class="weekaddtoday"';
           if($_GET['updatecal']) {
             $return .= ' onclick="addondateplain(\''.date("d/m/Y",$epochsecs).'\')"';
           } else {
             $onload .= 'listen(\'click\',\'mousehookaddday\',addondate(\''.date("d/m/Y",$epochsecs).'\'));'."\n";
           }
           $return .= '>'.STR_ADDEVENTON.' '.iz_longdate($epochsecs).'</a><br /><br />';
         }
         $return .= '<table class="largecontainer caldays dayviewallday">';
         if(($opt_flags & OPT_ENDDATE) != 0) {
         $return .= '<table class="largecontainer caldays"><tr class="titleback"><td colspan="2"><table class="spannav"><tr>
                <td><a href="'.getlink('dayprev',$day,$month,$year).'" title="'.STR_PREVIOUS.'" class="nicebutton">&lt;&lt;'. STR_NAVPREV.'</a></td>
                <td>'.STR_EVENTSON.' '.iz_longdate($epochsecs).'</td>
                <td><a href="'.getlink('daynext',$day,$month,$year).'" title="'.STR_NEXT.'" class="nicebutton">'. STR_NAVNEXT.'&gt;&gt;</a></td></tr></table></td></tr>';
         } else {
           $return .= '<tr><td class="titleback">'.STR_ALLDAYON.' '.iz_longdate($epochsecs).'</td></tr>';
         }
         $return .= get_events('allday',$epochsecs,'none');
         $return .= '</table>';
         if(($opt_flags & OPT_ENDDATE) != 0) {
           $return .= '<br /><br />
                 <table class="largecontainer caldays dayview"><tr class="titleback"><td colspan="2"><table class="spannav"><tr>
                 <td><a href="'.getlink('dayprev',$day,$month,$year).'" title="'.STR_PREVIOUS.'" class="nicebutton">&lt;&lt;'. STR_NAVPREV.'</a></td>
                 <td>'.iz_longdate($epochsecs).'</td>
                 <td><a href="'.getlink('daynext',$day,$month,$year).'" title="'.STR_NEXT.'" class="nicebutton">'. STR_NAVNEXT.'&gt;&gt;</a></td></tr></table></td></tr>';
           for($hour=0;$hour<24;$hour++) {
             $houroffset = 3600*$hour;
             $return .= '<tr><td class="dayhours">';
             if($hour<10) {
               $return .= '0'.$hour.':00';
             } else {
               $return .= $hour.':00';
             }
             $return .= '</td>';
             $return .= get_events('daynormal',$epochsecs,$houroffset);
             $return .= '</tr>';
           }
           $return .= '</table>';
         }
         return $return;
}
/**
* Returns the contents of a week as HTML.
* @param epochsecs The starting second of the week.
*/
function get_week($epochsecs) {
        global $daynames;
        global $numqs;
        global $onload;
        $firstdaynum = date('j',$epochsecs) - getOffsetDisplayedIndex(date('w',$epochsecs));
        $month = date('n',$epochsecs);
        $year = date('Y',$epochsecs);
        $return .= '
          <table cellpadding="0" id="calweeks">
            <tr class="titleback">
              <td colspan="2">
                <table class="spannav">
                  <tr>
                    <td><a href="'.getlink('weekprev',$firstdaynum,$month,$year).'" title="'.STR_PREVIOUS.'" class="nicebutton">&lt;&lt;'. STR_NAVPREV.'</a></td>
                    <td>'.STR_WEEKSTARTING.' '.iz_longdate(mktime(0,0,0,$month,$firstdaynum,$year)).'<br />'.STR_WEEK.' '.date('W',$epochsecs).'</td>
                    <td><a href="'.getlink('weeknext',$firstdaynum,$month,$year).'" title="'.STR_NEXT.'" class="nicebutton">'. STR_NAVNEXT.'&gt;&gt;</a></td>
                  </tr>
                </table>
              </td>
            </tr>';
        $return .= get_events('week',$epochsecs,'none');
        $return .= '
          </table>';
        return $return;
}
/**
* Returns the contents of a month as HTML.
* @param epochsecs The starting second of the month.
*/
function get_month($epochsecs,$nav,$linktitle,$ext = '') {
        global $weekdays;
        global $daynames;
        global $monthnames;
        global $onload;
        $month = date('n',$epochsecs);
        $year = date('Y',$epochsecs);        
        $firstdayofmonth = mktime(0,0,0,$month,1,$year);
        $lastdayofmonth = mktime(0,0,0,$month+1,1,$year) - 86400;
        $numdays = date('t',$firstdayofmonth);
        $monthname = $monthnames[date('n',$firstdayofmonth)];
        $firstvisiblecol = getOffsetDisplayedIndex(date('w',$firstdayofmonth));
        $lastvisiblecol = getOffsetDisplayedIndex(date('w',$lastdayofmonth));
        if($nav == 'nav') {
          $return .= '<table class="calbody">
                        <tr class="titleback"><td colspan="7" style="padding: 2px;">
                            <table class="spannav">
                              <tr><td><a href="'.getlink('monthprev',1,$month,$year,$ext).'" title="'.STR_PREVIOUS.'" class="nicebutton">&lt;&lt;</a></td>
                                <td>';
          if($linktitle == 'link') {
            $return .= '<a href="'.getlink('month',1,$month,$year,$ext).'">'.$monthname.' '.$year.'</a>';
          } else {
            $return .= $monthname.' '.$year;
          }
          $return .= '</td>
                      <td><a href="'.getlink('monthnext',1,$month,$year,$ext).'" title="'.STR_NEXT.'" class="nicebutton">&gt;&gt;</a></td></tr>
                  </table>
                </td></tr>
                <tr>';
        } else {
          $return .= '<table class="calbody"><tr><td colspan="7" class="titleback">';
          if($linktitle == 'link') {
            $return .= '<a href="'.getlink('month',1,$month,$year,$ext).'" title="'.STR_NEXT.'">'.$monthname.' '.$year.'</a>';
          } else {
            $return .= $monthname.' '.$year;
          }
          $return .= '</td></tr><tr>';
        }
        for($i=0;$i<7;$i++) {
          $name = $daynames[getLocalizedIndex($i)];
          $return .= '<td class="daynames" title="'.$name.'" abbr="'.$name.'">'.$weekdays[getLocalizedIndex($i)].'</td>';
        }
        $return .= '</tr><tr>'."\n";
        $colcount = 1;
        for($i=0;$i<$firstvisiblecol;$i++) {
          $return .= '<td class="fillerdays">&nbsp;</td>';
          $colcount++;
        }
        for($loopday = 1; $loopday<=$numdays; $loopday++) {
          if(($colcount == 7) && ($loopday < 31)) {
            $return .= get_events('month', $loopday, $firstdayofmonth,$ext);
            $return .= '</tr><tr>';
            $colcount = 1;
          } else {
            $return .= get_events('month', $loopday, $firstdayofmonth,$ext);
            $colcount++;
          }
        }
        for($i=$lastvisiblecol;$i<6;$i++) {
          $return .= '<td class="fillerdays">&nbsp;</td>';
        }
        $return .= '</tr></table>'."\n";
        return $return;
}
/**
* Returns the contents of a year as HTML.
* @param epochsecs The starting second of the year.
*/
function get_year($epochsecs) {
         global $onload;
         $year = date('Y',$epochsecs);
         $return .= '<table class="yeartable">
           <tr class="titleback"><td colspan="3">
             <table class="spannav">
               <tr><td><a href="'.getlink('yearprev','null','null',$epochsecs).'" title="'.STR_PREVIOUS.'" class="nicebutton">&lt;&lt;'. STR_NAVPREV.'</a></td>
               <td><h1>'.date('Y',$epochsecs).'</h1></td>
               <td><a href="'.getlink('yearnext','null','null',$epochsecs).'" title="'.STR_NEXT.'" class="nicebutton">'. STR_NAVNEXT.'&gt;&gt;</a></td></tr>
             </table>
           </td></tr>
           <tr>';
         for($month=1;$month<=12;$month++) {
           $return .= '<td><br />';
           $return .= get_month(mktime(0,0,0,$month,1,$year),'nonav','link');
           $return .= '</td>';
           if(($month % 3) == 0) {
             $return .= '</tr><tr>';
           }
         }
         $return .= '</tr></table>';
         return $return;
}
/**
* Returns a link to the next/previous period.
* @param type The link type (day/week/month/year)(prev/next)
* @param d The day
* @param m The week
* @param y The week
* @param ext Month view only - set this param to 'ext' if the link should be to the extended month. (default: standard month).
*/
function getlink($type,$d,$m,$y,$ext = '') {
     $day = intval($d);
     $month = intval($m);
     $year = intval($y);
     switch($type) {
         case 'month':
             $period = mktime(0,0,0,$month,$day,$year);
             $viewtype = $ext.'month'; 
             break;
         case 'monthnext':
             if($month == 12) {
               $period = mktime(0,0,0,1,$day,$year+1);
             } else {
               $period = mktime(0,0,0,$month+1,$day,$year);
             }
             $viewtype = $ext.'month';
             break;
         case 'monthprev':
             if($month == 0) {
               $period = mktime(0,0,0,12,$day,$year-1);
             } else {
               $period = mktime(0,0,0,$month-1,$day,$year);
             }
             $viewtype = $ext.'month';
             break;
         case 'week':
             $period = mktime(0,0,0,$month,$day,$year);
             $viewtype = 'week'; 
             break;
         case 'weeknext':
             $weeknum = date('W',mktime(0,0,0,$month,$day,$year));
             if($weeknum == 52) {
                 $period = mktime(0,0,0,$month,$day+7,$year);
             } else {
               $dayoffset = date('t',mktime(0,0,0,$month,$day,$year)) - $day;
               if($dayoffset > 7) {
                 $period = mktime(0,0,0,$month,$day+7,$year);
               } else {
                 $period = mktime(0,0,0,$month+1,7-$offset,$year);
               }
             }
             $viewtype = 'week';
             break;
         case 'weekprev':
             $weeknum = date('W',mktime(0,0,0,$month,$day,$year));
             if($weeknum == 0) {
               $period = mktime(0,0,0,12,31,$year-1);
             } else {
               $dayoffset = 7 - $day;
               if($dayoffset > 7) {
                 $period = mktime(0,0,0,$month,$day-7,$year);
               } else {
                 $period = mktime(0,0,0,$month-1,date('t',mktime(0,0,0,$month,0,$year))-$dayoffset,$year);
               }
             }
             $viewtype = 'week';
             break;
         case 'day':
             $period = mktime(0,0,0,$month,$day,$year);
             $viewtype = 'day'; 
             break;
         case 'daynext':
            if($day == date('t',mktime(0,0,0,$month,$day,$year))) {
              if($month == 12) {
                $period = mktime(0,0,0,1,1,$year+1);
              } else {
                $period = mktime(0,0,0,$month+1,1,$year);
              }
            } else {
              $period = mktime(0,0,0,$month,$day+1,$year);
            }
            $viewtype = 'day';
            break;
         case 'dayprev':
            if($day == 1) {
              if($month == 1) {
                $period = mktime(0,0,0,12,31,$year-1);
              } else {
                $period = mktime(0,0,0,$month,0,$year);
              }
            } else {
              $period = mktime(0,0,0,$month,$day-1,$year);
            }
            $viewtype = 'day';
            break;
         case 'year':
             $period = mktime(0,0,0,1,1,$year);
             $viewtype = 'year'; 
             break;
         case 'yearprev':
           $prevyear = date('Y',$year)-1;
           $period = mktime(0,0,0,1,1,$prevyear);
           $viewtype = 'year';
           break;
         case 'yearnext':
           $nextyear = date('Y',$year)+1;
           $period = mktime(0,0,0,1,1,$nextyear);
           $viewtype = 'year';
           break;
     }
     $day = date('j',$period);
     $month = date('n',$period);
     $year = date('Y',$period);
     if($_SESSION['IZ_REWRITE'] == 'apache') {
       return $_SESSION['IZ_CALURL'].$viewtype.'/'.$year.'/'.str_pad($month,2,'0',STR_PAD_LEFT).'/'.str_pad($day,2,'0',STR_PAD_LEFT).'/';
     } else {
       return 'index.php?view='.$viewtype.'&amp;day='.$day.'&amp;month='.$month.'&amp;year='.$year;
     }
}
/**
* Returns the number of events occuring between the given period
*/
function get_num_events($startdate,$enddate) {
         global $numqs;
         izsql();
         if($_SESSION['cpanel'] == 1) {
           $eventsql = "SELECT * FROM events WHERE (eventstart BETWEEN '".$startdate."' AND '".$enddate."')";
         } else {
           $eventsql = "SELECT * FROM events WHERE (eventstart BETWEEN '".$startdate."' AND '".$enddate."') AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")";
         }
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $res = $dblink->query($eventsql);
             $eventnum = $res->num_rows;
             $res->close();
           } else {
             $eventqry = mysql_query($eventsql);
             if(is_resource($eventqry)) {
               $eventnum = mysql_num_rows($eventqry);
             } else {
               $eventnum = 0;
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM \"events\" WHERE (\"eventstart\" BETWEEN '".$startdate."' AND '".$enddate."')";
           } else {
             $eventsql = "SELECT * FROM \"events\" WHERE (\"eventstart\" BETWEEN '".$startdate."' AND '".$enddate."') AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")";
           }
           $eventqry = pg_query($eventsql);
           if(is_resource($eventqry)) {
             $eventnum = pg_num_rows($eventqry);
           } else {
             $eventnum = 0;
           }
         } elseif(IZ_CALMODE == 'msq') {
           $eventqry = mssql_query($eventsql);
           if(is_resource($eventqry)) {
             $eventnum = mssql_num_rows($eventqry);
           } else {
             $eventnum = 0;
           }
         }
         $numqs++;
         return $eventnum;
}
/**
* Returns the number of events visible to the user using the currently selected filters.
*/
function get_num_visible($startdate,$enddate) {
         global $numqs;
         izsql();
         if($_SESSION['cpanel'] == 1) {
           $eventsql = "SELECT * FROM events WHERE (eventstart BETWEEN '".$startdate."' AND '".$enddate."')".$_SESSION['eventcats']['filters'];
         } else {
           $eventsql = "SELECT * FROM events WHERE (eventstart BETWEEN '".$startdate."' AND '".$enddate."') AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters'];
         }
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $res = $dblink->query($eventsql);
             $eventnum = $res->num_rows;
             $res->close();
           } else {
             $eventqry = mysql_query($eventsql);
             if(is_resource($eventqry)) {
               $eventnum = mysql_num_rows($eventqry);
             } else {
               $eventnum = 0;
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM \"events\" WHERE (\"eventstart\" BETWEEN '".$startdate."' AND '".$enddate."')".$_SESSION['eventcats']['filters'];
           } else {
             $eventsql = "SELECT * FROM \"events\" WHERE (\"eventstart\" BETWEEN '".$startdate."' AND '".$enddate."') AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters'];
           }
           $eventqry = pg_query($eventsql);
           if(is_resource($eventqry)) {
             $eventnum = pg_num_rows($eventqry);
           } else {
             $eventnum = 0;
           }
         } elseif(IZ_CALMODE == 'msq') {
           $eventqry = mssql_query($eventsql);
           if(is_resource($eventqry)) {
             $eventnum = mssql_num_rows($eventqry);
           } else {
             $eventnum = 0;
           }
         }
         $numqs++;
         return $eventnum;
}
/**
* Returns the events occuring in a period in a set format.
* Internal function used by functions.php 
* @param period The starting second of the period to display
* @param par1 Varies depending in type
* @param par2 Varies depending in type
* @param ext Month view only - set this param to 'ext' to display the extended month. (default: standard month).
*/
function get_events($period, $par1, $par2,$ext = '') {
         global $numqs;
         global $curDay;
         global $curMonth;
         global $curYear;
         global $itemno;
         global $icons;
         global $onload;
         $opt_flags = $_SESSION['IZ_OPT'];
         izsql();
         if($period == 'month') {
            $periodstart = mktime(0,0,0,date('n',$par2),$par1,date('Y',$par2));
            $periodend = mktime(23,59,59,date('n',$par2),$par1,date('Y',$par2));
            $fromday = date('j',$par2);
            $frommonth = date('n',$par2);
            $fromyear = date('Y',$par2);
            $events = array();
            if($_SESSION['cpanel'] == 1) {
              $eventsql = "SELECT * FROM events WHERE (( eventstart BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventstart < '".$periodstart."' AND eventend > '".$periodend."' ))";
              if($_SESSION['showall'] == 0) {
                $eventsql .= " AND (LOWER(author) = '".strtolower($_SESSION['uname'])."') ";
              }
              $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY eventstart';
            } else {
              $eventsql = "SELECT * FROM events WHERE ((( eventstart BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventstart < '".$periodstart."' AND eventend > '".$periodend."' )) AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY eventstart';
            }
            if(IZ_CALMODE == 'mysql') {
              if($_SESSION['MYSQLi']) {
                global $dblink;
                $res = $dblink->query($eventsql);
                if($res->num_rows > 0) {
                  while($sqlevent = $res->fetch_object()) {
                    $events[] = new event($sqlevent);
                  }
                }
              } else {
                $eventqry = mysql_query($eventsql);
                if(is_resource($eventqry)) {
                  while($sqlevent = mysql_fetch_object($eventqry)) {
                    $events[] = new event($sqlevent);
                  }
                }
              }
            } elseif(IZ_CALMODE == 'postgre') {
              if($_SESSION['cpanel'] == 1) {
                $eventsql = 'SELECT * FROM "events" WHERE (( "eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."') OR (\"eventstart\" < '".$periodstart."' AND \"eventend\" > '".$periodend."' ))";
                if($_SESSION['showall'] == 0) {
                  $eventsql .= ' AND ("LOWER(author) = \''.strtolower($_SESSION['uname'])."') ";
                }
                $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY "eventstart"';
              } else {
                $eventsql = 'SELECT * FROM "events" WHERE ((( "eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."') OR (\"eventstart\" < '".$periodstart."' AND \"eventend\" > '".$periodend."' )) AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY "eventstart"';
              }
              $eventqry = pg_query($eventsql);
              if(is_resource($eventqry)) {
                while($sqlevent = pg_fetch_object($eventqry)) {
                  $events[] = new event($sqlevent);
                }
              }
            } elseif(IZ_CALMODE == 'msq') {
              $eventqry = mssql_query($eventsql);
              if(is_resource($eventqry)) {
                while($sqlevent = mssql_fetch_object($eventqry)) {
                  $events[] = new event($sqlevent);
                }
              }
            }
            $numqs++;
            $eventnum = count($events);
            if($ext == '') { // plain month view
              $return .= '<td id="mousehook'.$itemno.'" class="';
              if($periodstart == mktime(0,0,0,$curMonth,$curDay,$curYear)) {
                $return .= 'caltoday ';
              }
              if($eventnum > 0) {
                  $return .= 'occupiedday"';
                  if($_GET['updatecal']) {
                    $return .= ' onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')"';
                  } else {
                    $onload .= 'listen(\'mouseover\',\'mousehook'.$itemno.'\',overlayfunc(\''.$itemno.'\',\'event\'));'."\n".
                               'listen(\'mouseout\',\'mousehook'.$itemno.'\',closefunc(\''.$itemno.'\',\'event\'));'."\n";
                  }
                  $return .= '><a href="'.getlink('day',date('j',$periodstart),date('n',$periodstart),date('Y',$periodstart)).'"><span class="daynum">'.$par1.'</span></a>';
                  $return .= '<div id="event'.$itemno.'" class="eventdiv"><div class="title"><strong>'.iz_longdate($periodstart).'</strong></div><div class="popupcontainer">';
                  foreach($events as $event) {
                    if($event->allday == 1) {
                      $duration = calcduration($event->eventstart,$event->eventend,true,STR_ALLDAYSHORT);
                    } else {
                      $duration = calcduration($event->eventstart,$event->eventend);
                    }
                    $return .= '<span class="';
                    switch($_SESSION['IZ_ITEMCOLORS']) {
                      case 'c':
                        $return .= 'cat-'.$event->category;
                        break;
                      case 'a':
                        $return .= 'item-'.$event->author;
                        break;
                      case 't':
                        $return .= 'itemtitle';
                        break;
                    }
                    $return .= '"><a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=view-month.month-'.$frommonth.'.year-'.$fromyear.'">';
                    if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                      $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$event->icon].'" class="icon" />';
                    }
                    $return .='<strong>'.$event->title.'</strong></a></span><br />';
                    if(($opt_flags & OPT_ENDDATE) != 0) {
                      if($event->allday != 1) { 
                        $return .= '<strong>'.STR_STARTS.'&#58;</strong> '.date("H:i",$event->eventstart).'<br />';
                      }
                      if($duration != '0m') {
                        $return .= '<strong>'.STR_DURATION.'&#58;</strong> '.$duration.'<br />';
                      }
                    } else {
                      $return .= '<strong>'.STR_STARTS.'&#58;</strong> '.date("H:i",$event->eventstart).'<br />';
                    }
                    if(($event->cust1 != '') && ($_SESSION['cust1'] != 'none')) {
                      $return .= '<strong>'.$_SESSION['cust1'].'&#58;</strong> '.$event->cust1.'<br />';
                    }
                    if(($event->cust2 != '') && ($_SESSION['cust2'] != 'none')) {
                      $return .= '<strong>'.$_SESSION['cust2'].'&#58;</strong> '.$event->cust2.'<br />';
                    }
                    if(($event->cust3 != '') && ($_SESSION['cust3'] != 'none')) {
                      $return .= '<strong>'.$_SESSION['cust3'].'&#58;</strong> '.$event->cust3.'<br />';
                    }
                    if((!empty($event->venue)) && (($opt_flags & OPT_VENUE) != 0)) {
                      $return .= '<strong>'.STR_VENUE.'&#58;</strong> ';
                        if(($event->linkgoogle == 1) && (($opt_flags & OPT_GOOGLE) != 0)) {
                          $return .= '<a href="http://maps.google.co.uk/maps?q='.$event->venue.'" title="'.STR_LINKGOOGLE.'"'.(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : '').'>'.$event->venue.'</a>';
                        } else {
                          $return .= $event->venue;
                        }                    
                      $return .= '<br />';
                    }
                    if($_SESSION['cpanel'] == 1) {
                      if(strtolower($event->author) == 'everyone') {
                        $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.STR_NOTLOGGEDIN.'<br />';
                      } else {
                        $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.$event->author.'<br />';
                      }
                    }
                    if(strlen($event->description)>100) {
                      $return .= substr(strip_tags($event->description),0,100)."...";
                    } else {
                      $return .= '<div class="description">'.$event->description.'</div>';
                    }
                    $return .= '<br /><br />';
                  }
                  if($_SESSION['edit'] > 0) { 
                    $return .= '<a id="add'.$periodstart.'" href="'.$_SESSION['IZ_CALURL'].'index.php?act=add&amp;adddate='.date("d-m-Y",$epochsecs).'" title="'.STR_ADDEVENT.'" class="addtoday"';
                    if($_GET['updatecal']) {
                      $return .= ' onclick="addondateplain(\''.date("d/m/Y",$periodstart).'\')"';
                    } else {
                      $onload .= 'listen(\'click\',\'add'.$periodstart.'\',addondate(\''.date("d/m/Y",$periodstart).'\'));'."\n";
                    }
                    $return .= '>'.STR_ADDEVENT.'</a>';
                  }
              } else {
                $return .= 'blankday"';
                if($_GET['updatecal']) {
                  $return .= ' onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')"';
                } else {
                  $onload .= "listen('mouseover','mousehook$itemno',overlayfunc('$itemno','event'))\nlisten('mouseout','mousehook$itemno',closefunc('$itemno','event'))\n";
                }
                $return .= '><a href="'.getlink('day',date('j',$periodstart),date('n',$periodstart),date('Y',$periodstart)).'"><span class="daynum">'.$par1.'</span></a><div id="event'.$itemno.'" class="eventdiv"><div class="title"><strong>'.iz_longdate($periodstart).'</strong></div><div class="popupcontainer">'.STR_NOEVENTS.'
                     <br /><br />';
                if($_SESSION['edit'] > 0) {
                  $return .= '<a id="add'.$periodstart.'" href="'.$_SESSION['IZ_CALURL'].'index.php?act=add&amp;adddate='.date("d-m-Y",$periodstart).'" title="'.STR_ADDEVENT.'" class="addtoday"';
                  if($_GET['updatecal']) {
                    $return .= ' onclick="addondateplain(\''.date("d/m/Y",$periodstart).'\')"';
                  } else {
                    $onload .= 'listen(\'click\',\'add'.$periodstart.'\',addondate(\''.date("d/m/Y",$periodstart).'\'));'."\n";
                  }
                  $return .= '>'.STR_ADDEVENT.'</a>';
                }              
              }
              $return .= '</div></div></td>'."\n";
            } else { // extended month view
              $return .= '<td class="';
              if($periodstart == mktime(0,0,0,$curMonth,$curDay,$curYear)) {
                $return .= 'caltoday ';
              }
              if($eventnum > 0) {
                $return .= 'occupiedday">';
                if($_SESSION['edit'] > 0) {
                  $return .= '<a id="add'.$periodstart.'" href="'.$_SESSION['IZ_CALURL'].'index.php?act=add&amp;adddate='.date("d-m-Y",$periodstart).'" title="'.STR_ADDEVENT.'" class="addtodayext"';
                  if($_GET['updatecal']) {
                    $return .= ' onclick="addondateplain(\''.date("d/m/Y",$periodstart).'\');"';
                  } else {
                    $onload .= 'listen(\'click\',\'add'.$periodstart.'\',addondate(\''.date("d/m/Y",$periodstart).'\'));'."\n";
                  }
                  $return .= '><span class="addtext">'.STR_ADDEVENT.'</span><img src="'.$_SESSION['IZ_CALURL'].'includes/themes/add.gif" alt="'.STR_ADDEVENT.'" /></a>';
                }
                $return .= '<a href="'.getlink('day',date('j',$periodstart),date('n',$periodstart),date('Y',$periodstart)).'"><span class="daynum">'.$par1.'</span></a>';
                foreach($events as $event) {
                    if($event->allday == 1) {
                      $duration = calcduration($event->eventstart,$event->eventend,true,STR_ALLDAYSHORT);
                    } else {
                      $duration = calcduration($event->eventstart,$event->eventend);
                    }
                    $return .= '<div class="extview"><span class="';
                    switch($_SESSION['IZ_ITEMCOLORS']) {
                      case 'c':
                        $return .= 'cat-'.$event->category;
                        break;
                      case 'a':
                        $return .= 'item-'.$event->author;
                        break;
                      case 't':
                      default:
                        $return .= 'itemtitle';
                        break;
                    }
                    $return .= '"><a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=view-extmonth.month-'.$frommonth.'.year-'.$fromyear.'">';
                    if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                      $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$event->icon].'" class="icon" />';
                    }
                    $return .= '<strong>'.$event->title.'</strong></a></span><br />';
                    if(($opt_flags & OPT_ENDDATE) != 0) {
                      if($event->allday == 1) {
                        $return .= '<em>'.calcduration($event->eventstart,$event->eventend,true,STR_ALLDAYSHORT).'</em><br />';
                      } else {
                        if($duration == '0m') {
                          $return .= '<em>'.date("H:i",$event->eventstart).'</em><br />';
                        } else {
                          $return .= '<em>'.date("H:i",$event->eventstart).' - '.date("H:i",$event->eventend).'</em><br />';
                        }
                      }
                    }
                    if((!empty($event->venue)) && (($opt_flags & OPT_VENUE) != 0)) {
                      if(($event->linkgoogle == 1) && (($opt_flags & OPT_VENUE) != 0)) {
                        $return .= '<a href="http://maps.google.co.uk/maps?q='.$event->venue.'" title="'.$event->venue.'"'.(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : '').'>'.$event->venue.'</a>';
                      } else {
                        $return .= $event->venue;
                      }                    
                      $return .= '<br />';
                    }
                    $return .= '</div>';
                }
              } else {
                $return .= 'blankday">';
                if($_SESSION['edit'] > 0) {
                  $return .= '<a id="add'.$periodstart.'" href="'.$_SESSION['IZ_CALURL'].'index.php?act=add&amp;adddate='.date("d-m-Y",$periodstart).'" title="'.STR_ADDEVENT.'" class="addtodayext"';
                  if($_GET['updatecal']) {
                    $return .= ' onclick="addondateplain(\''.date("d/m/Y",$periodstart).'\')"';
                  } else {
                    $onload .= 'listen(\'click\',\'add'.$periodstart.'\',addondate(\''.date("d/m/Y",$periodstart).'\'));'."\n";
                  }
                  $return .= '><span class="addtext">'.STR_ADDEVENT.'</span><img src="'.$_SESSION['IZ_CALURL'].'includes/themes/add.gif" alt="'.STR_ADDEVENT.'" /></a>';
                }
                $return .= '<a href="'.getlink('day',date('j',$periodstart),date('n',$periodstart),date('Y',$periodstart)).'"><span class="daynum">'.$par1.'</span></a>';
                
              }
              $return .= '</td>'."\n";
            }
            $itemno++;
         } elseif($period == 'daynormal') {
            $daystart = mktime(0,0,0,date('n',$par1),date('j',$par1),date('Y',$par1));
            $periodstart = $daystart+$par2;
            $periodend = $periodstart + 3599;
            $fromday = date('j',$par1);
            $frommonth = date('n',$par1);
            $fromyear = date('Y',$par1);            
            $events = array();           
            if($_SESSION['cpanel'] == 1) {
              $eventsql = "SELECT * FROM events WHERE allday != 1 AND (( eventstart BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventstart < '".$periodstart."' AND eventend > '".$periodend."' ))";
              if($_SESSION['showall'] == 0) {
                $eventsql .= " AND (LOWER(author) = '".strtolower($_SESSION['uname'])."') ";
              }
              $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY eventstart';
            } else {
              $eventsql = "SELECT * FROM events WHERE allday != 1 AND ((( eventstart BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventstart < '".$periodstart."' AND eventend > '".$periodend."' )) AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY eventstart';
            }
            if(IZ_CALMODE == 'mysql') {
              if($_SESSION['MYSQLi']) {
                global $dblink;
                $res = $dblink->query($eventsql);
                if($res->num_rows > 0) {
                  while($sqlevent = $res->fetch_object()) {
                    $events[] = new event($sqlevent);
                  }
                }
                $res->close();
              } else {
                $eventqry = mysql_query($eventsql);
                if(is_resource($eventqry)) {
                  while($sqlevent = mysql_fetch_object($eventqry)) {
                    $events[] = new event($sqlevent);
                  }
                }
              }
            } elseif(IZ_CALMODE == 'postgre') {
              if($_SESSION['cpanel'] == 1) {
                $eventsql = 'SELECT * FROM "events" WHERE "allday" != 1 AND (( "eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."') OR (\"eventstart\" < '".$periodstart."' AND \"eventend\" > '".$periodend."' ))";
                if($_SESSION['showall'] == 0) {
                  $eventsql .= ' AND ("author" = \''.strtolower($_SESSION['uname'])."') ";
                }
                $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY "eventstart"';
              } else {
                $eventsql = 'SELECT * FROM "events" WHERE "allday" != 1 AND ((( "eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."')) AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY \"eventstart\"';
              }
              $eventqry = pg_query($eventsql);
              if(is_resource($eventqry)) {
                while($sqlevent = pg_fetch_object($eventqry)) {
                  $events[] = new event($sqlevent);
                }
              }
            } elseif(IZ_CALMODE == 'msq') {
              $eventqry = mssql_query($eventsql);
              if(is_resource($eventqry)) {
                while($sqlevent = mssql_fetch_object($eventqry)) {
                  $events[] = new event($sqlevent);
                }              
              }
            }
            $numqs++;
            $eventnum = count($events);
            if($eventnum > 0) {
                $return .= '<td class="occupiedhour rightcell">';
                foreach($events as $event) {
                  $return .= '<h4><span class="';
                  switch($_SESSION['IZ_ITEMCOLORS']) {
                    case 'c':
                      $return .= 'cat-'.$event->category;
                      break;
                    case 'a':
                      $return .= 'item-'.$event->author;
                      break;
                    case 't':
                      $return .= 'itemtitle';
                      break;
                  }
                  $return .= '">';
                  if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                    $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$event->icon].'" class="icon" />';
                  }
                  $return .= '<a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=view-day.day-'.$fromday.'.month-'.$frommonth.'.year-'.$fromyear.'">'.$event->title;
                  if($event->eventstart == $event->eventend) {
                    $return .= ' &#40;'.date("H:i",$event->eventstart).'&#41;</a></span></h4>';
                  } else {
                    $return .= ' &#40;'.date("H:i",$event->eventstart).' - '.date("H:i",$event->eventend).'&#41;</a></span></h4>';
                  }
                  if((($opt_flags & OPT_ATTENDEES) != 0) && (!empty($event->attendees))) {
                    $return .= '<strong>'.STR_ATTENDEES.'&#58;</strong> '.$event->attendees.'<br />';
                  }
                  if(($event->cust1 != '') && ($_SESSION['cust1'] != 'none')){
                    $return .= '<strong>'.$_SESSION['cust1'].'&#58; </strong>'.$event->cust1.'<br />';
                  }
                  if(($event->cust2 != '') && ($_SESSION['cust2'] != 'none')){
                    $return .= '<strong>'.$_SESSION['cust2'].'&#58; </strong>'.$event->cust2.'<br />';
                  }
                  if(($event->cust3 != '') && ($_SESSION['cust3'] != 'none')){
                    $return .= '<strong>'.$_SESSION['cust3'].'&#58; </strong>'.$event->cust3.'<br />';
                  }
                  if((($opt_flags & OPT_VENUE) != 0) && (!empty($event->venue))) {
                    $return .= '<strong>'.STR_VENUE.'&#58;</strong> '.$event->venue.'<br />';
                  }
                  if($_SESSION['cpanel'] == 1) {
                    if(strtolower($event->author) == 'everyone') {
                      $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.STR_NOTLOGGEDIN.'<br />';
                    } else {
                      $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.$event->author.'<br />';
                    }
                  }
                  if(($opt_flags & OPT_CATEGORY) != 0) {
                    if(empty($_SESSION['eventcats'][$event->category]->name)) {
                      $return .= '<strong>'.STR_CATEGORY.'&#58; </strong>'.STR_PRIVATE.'<br />';
                    } else {
                      if($_SESSION['IZ_REWRITE'] == 'apache') {
                        $return .= '<strong>'.STR_CATEGORY.'&#58; </strong><a href="'.$_SESSION['IZ_CALURL'].'/category/'.$event->category.'/">'.$_SESSION['eventcats'][$event->category]->name.'</a><br />';
                      } else {
                        $return .= '<strong>'.STR_CATEGORY.'&#58; </strong><a href="'.$_SESSION['IZ_CALURL'].'index.php?category='.$event->category.'">'.$_SESSION['eventcats'][$event->category]->name.'</a><br />';
                      }
                    }
                  }
                  if(!empty($event->description)) {
                    $return .= '<div class="description">'.$event->description.'</div><br />';
                  }
                }
                $return .= '</td>';
            } else {
                $return .= '<td class="blankhour">&nbsp;</td>';
            }
          } elseif($period == 'allday') {
                $periodstart = mktime(0,0,0,date('n',$par1),date('j',$par1),date('Y',$par1));
                $periodend = $periodstart + 86399;
                $fromday = date('j',$par1);
                $frommonth = date('n',$par1);
                $fromyear = date('Y',$par1);
                $events = array();
                
                if($_SESSION['cpanel'] == 1) {
                  // Because all-day/part day events are shown separately, this query shows all events which are set to all day and fall within the bounds of the day
                  // and events which aren't explicitly set all day, but span the whole day (start before the day and end after the day)
                  $eventsql = "SELECT * FROM events WHERE (allday = 1 AND (( eventstart BETWEEN '".$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."'))) OR (allday != 1 AND (eventstart < '".$periodstart."' AND eventend > '".$periodend."' ))";
                  if($_SESSION['showall'] == 0) {
                    $eventsql .= " AND (LOWER(author) = '".strtolower($_SESSION['uname'])."') ";
                  }
                  $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY eventstart';
                } else {
                  $eventsql = 'SELECT * FROM events WHERE ((LOWER(author) = \''.strtolower($_SESSION['uname']).'\')'.$_SESSION['publicstatus'].')'.$_SESSION['eventcats']['filters'].' AND ((allday = 1 AND (( eventstart BETWEEN \''.$periodstart."' AND '".$periodend."') OR (eventend BETWEEN '".$periodstart."' AND '".$periodend."'))) OR (allday != 1 AND (eventstart < '".$periodstart."' AND eventend > '".$periodend."' ))) ORDER BY eventstart";
                }
                if(IZ_CALMODE == 'mysql') {
                  if($_SESSION['MYSQLi']) {
                    global $dblink;
                    $res = $dblink->query($eventsql);
                    if($res->num_rows > 0) {
                      while($sqlevent = $res->fetch_object()) {
                        $events[] = new event($sqlevent);
                      }
                    }
                  } else {
                    $eventqry = mysql_query($eventsql);
                    if(is_resource($eventqry)) {
                      while($sqlevent = mysql_fetch_object($eventqry)) {
                        $events[] = new event($sqlevent);
                      }
                    }
                  }
                } elseif(IZ_CALMODE == 'postgre') {
                  if($_SESSION['cpanel'] == 1) {
                    // Because all-day/part day events are shown separately, this query shows all events which are set to all day and fall within the bounds of the day
                    // and events which aren't explicitly set all day, but span the whole day (start before the day and end after the day)
                    $eventsql = 'SELECT * FROM "events" WHERE ("allday" = 1 AND (( "eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."'))) OR (\"allday\" != 1 AND (\"eventstart\" < '".$periodstart."' AND \"eventend\" > '".$periodend."' ))";
                    if($_SESSION['showall'] == 0) {
                      $eventsql .= ' AND ("author" = \''.strtolower($_SESSION['uname'])."') ";
                    }
                    $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY "eventstart"';
                  } else {
                    $eventsql = 'SELECT * FROM "events" WHERE (("author" = \''.strtolower($_SESSION['uname']).'\')'.$_SESSION['publicstatus'].')'.$_SESSION['eventcats']['filters'].' AND (("allday" = 1 AND (("eventstart" BETWEEN \''.$periodstart."' AND '".$periodend."') OR (\"eventend\" BETWEEN '".$periodstart."' AND '".$periodend."'))) OR (\"allday\" != 1 AND (\"eventstart\" < '".$periodstart."' AND \"eventend\" > '".$periodend."' ))) ORDER BY \"eventstart\"";
                  }
                  $eventqry = pg_query($eventsql);
                  if(is_resource($eventqry)) {
                    while($sqlevent = pg_fetch_object($eventqry)) {
                      $events[] = new event($sqlevent);
                    }              
                  }
                } elseif(IZ_CALMODE == 'msq') {
                  $eventqry = mssql_query($eventsql);
                  if(is_resource($eventqry)) {
                    while($sqlevent = mssql_fetch_object($eventqry)) {
                      $events[] = new event($sqlevent);
                    }              
                  }
                }
                $numqs++;
                $eventnum = count($events);
                if($eventnum > 0) {
                  foreach($events as $event) {
                      $return .= '<tr><td class="blankhour">
                                  <h4><span class="';
                      switch($_SESSION['IZ_ITEMCOLORS']) {
                        case 'c':
                          $return .= 'cat-'.$event->category;
                          break;
                        case 'a':
                          $return .= 'item-'.$event->author;
                          break;
                        case 't':
                          $return .= 'itemtitle';
                          break;
                      }
                      $return .= '">';
                      if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                        $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$event->icon].'" class="icon" />';
                      }
                      $return .= '<a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=view-day.day-'.$fromday.'.month-'.$frommonth.'.year-'.$fromyear.'">'.$event->title.'</a></span></h4>';
                      if(!empty($event->venue)) {
                        $return .= '<strong>'.STR_VENUE.'&#58;</strong> ';
                          if($event->linkgoogle == 1) {
                            $return .= '<a href="http://maps.google.co.uk/maps?q='.$event->venue.'" title="'.STR_LINKGOOGLE.'"'.(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : '').'>'.$event->venue.'</a>';
                          } else {
                            $return .= $event->venue;
                          }
                          $return .= '<br />'."\n";
                      }
                      if(($opt_flags & OPT_CATEGORY) != 0) {
                        if(empty($_SESSION['eventcats'][$event->category]->name)) {
                            $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> '.STR_PRIVATE.'<br />'."\n";
                        } else {
                          if($_SESSION['IZ_REWRITE'] == 'apache') {
                            $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> <a href="'.$_SESSION['IZ_CALURL'].'/category/'.$event->category.'/">'.$_SESSION['eventcats'][$event->category]->name.'</a><br />'."\n";
                          } else {
                            $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> <a href="'.$_SESSION['IZ_CALURL'].'index.php?category='.$event->category.'">'.$_SESSION['eventcats'][$event->category]->name.'</a><br />'."\n";
                          }
                        }
                      }
                      if((!empty($event->cust1)) && ($_SESSION['cust1'] != 'none')){
                        $return .= ' (<strong>'.$_SESSION['cust1'].'&#58; </strong> '.$event->cust1.')<br />'."\n";
                      }
                      if((!empty($event->cust2)) && ($_SESSION['cust2'] != 'none')){
                        $return .= ' (<strong>'.$_SESSION['cust2'].'&#58; </strong> '.$event->cust2.')<br />'."\n";
                      }
                      if((!empty($event->cust3)) && ($_SESSION['cust3'] != 'none')){
                        $return .= ' (<strong>'.$_SESSION['cust3'].'&#58; </strong> '.$event->cust3.')<br />'."\n";
                      }
                      if($_SESSION['cpanel'] == 1) {
                        if(strtolower($event->author) == 'everyone') {
                          $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.STR_NOTLOGGEDIN.'<br />'."\n";
                        } else {
                          $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.$event->author.'<br />'."\n";
                        }
                      }
                      $return .= '<div class="description">'.$event->description."</div>\n</td>\n\n\n\n\n";
                  }
                } else {
                    $return .= '<tr><td class="blankhour">'.STR_NOALLDAY.'</td></tr>'."\n";
                }
         } elseif($period == 'week') {
            global $daynames;
            $firstdaynum = date('j',$par1) - getOffsetDisplayedIndex(date('w',$par1));
            $fromday = date('j',$par1);
            $frommonth = date('n',$par1);
            $fromyear = date('Y',$par1);            
            $firstdaysecs = mktime(0,0,0,date('n',$par1),$firstdaynum,date('Y',$par1));
            $endweeksecs = mktime(23,59,59,date('n',$par1),$firstdaynum+6,date('Y',$par1));
            for($daynum=0;$daynum<7;$daynum++) {
              $daystart = $firstdaysecs + ($daynum*86400);
              $dayend = $daystart + 86399;
              $colspan = 0;
              $return .= '<tr><td class="weekdaynames">
                       <a href="'.getlink('day',date('j',$daystart),date('n',$daystart),date('Y',$daystart)).'">';
              $return .= $daynames[getLocalizedIndex($daynum)].' ';
              if($_SESSION['IZ_LANG'] == 'en') {
                $return .= date("jS",$daystart);
              } else {
                global $monthnames;
                $return .= date('j',$daystart).' '.$monthnames[date('n',$daystart)];
              }
              $return .= "</a>\n</td><td class=\"day\">\n";
              $events = array();
              $alldayevents = array();
              
              if($_SESSION['cpanel'] == 1) {
                $eventsql = "SELECT * FROM events WHERE (( eventstart BETWEEN '".$daystart."' AND '".$dayend."') OR (eventend BETWEEN '".$daystart."' AND '".$dayend."') OR (eventstart < '".$daystart."' AND eventend > '".$dayend."' ))";
                if($_SESSION['showall'] == 0) {
                  $eventsql .= " AND (LOWER(author) = '".strtolower($_SESSION['uname'])."') ";
                }
                $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY eventstart';
              } else {
                $eventsql = "SELECT * FROM events WHERE ((( eventstart BETWEEN '".$daystart."' AND '".$dayend."') OR (eventend BETWEEN '".$daystart."' AND '".$dayend."') OR (eventstart < '".$daystart."' AND eventend > '".$dayend."' )) AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY eventstart';
              }
              if(IZ_CALMODE == 'mysql') {
                if($_SESSION['MYSQLi']) {
                  global $dblink;
                  $res = $dblink->query($eventsql);        
                    while($sqlevent = $res->fetch_object()) {
                      $event = new event($sqlevent);
                      if($event->allday == 1 || ($event->eventstart < $daystart || $event->eventend > $dayend)) {
                          $alldayevents[] = $event;
                      } else {
                          $events[] = $event;
                      }
                    }
                  $res->close();
                } else {
                  $eventqry = mysql_query($eventsql);
                  if(is_resource($eventqry)) {
                    while($sqlevent = mysql_fetch_object($eventqry)) {
                      $event = new event($sqlevent);
                      if($event->allday == 1 || ($event->eventstart < $daystart || $event->eventend > $dayend)) {
                          $alldayevents[] = $event;
                      } else {
                          $events[] = $event;
                      }
                    }
                  }
                }
              } elseif(IZ_CALMODE == 'postgre') {
                if($_SESSION['cpanel'] == 1) {
                  $eventsql = 'SELECT * FROM "events" WHERE (( "eventstart" BETWEEN \''.$daystart."' AND '".$dayend."') OR (\"eventend\" BETWEEN '".$daystart."' AND '".$dayend."') OR (\"eventstart\" < '".$daystart."' AND \"eventend\" > '".$dayend."' ))";
                  if($_SESSION['showall'] == 0) {
                    $eventsql .= ' AND ("author" = \''.strtolower($_SESSION['uname'])."') ";
                  }
                  $eventsql .= $_SESSION['eventcats']['filters'].' ORDER BY "eventstart"';
                } else {
                  $eventsql = 'SELECT * FROM "events" WHERE ((( "eventstart" BETWEEN \''.$daystart."' AND '".$dayend."') OR (\"eventend\" BETWEEN '".$daystart."' AND '".$dayend."') OR (\"eventstart\" < '".$daystart."' AND \"eventend\" > '".$dayend."' )) AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'].' ORDER BY \"eventstart\"';
                }
                $eventqry = pg_query($eventsql);
                if(is_resource($eventqry)) {                  
                  while($sqlevent = pg_fetch_object($eventqry)) {
                    $event = new event($sqlevent);
                      if($event->allday == 1 || ($event->eventstart < $daystart || $event->eventend > $dayend)) {
                        $alldayevents[] = $event;
                    } else {
                        $events[] = $event;
                    }
                  }
                }
              } elseif(IZ_CALMODE == 'msq') {
                $eventqry = mssql_query($eventsql);
                if(is_resource($eventqry)) {                  
                  while($sqlevent = mssql_fetch_object($eventqry)) {
                    $event = new event($sqlevent);
                      if($event->allday == 1 || ($event->eventstart < $daystart || $event->eventend > $dayend)) {
                        $alldayevents[] = $event;
                    } else {
                        $events[] = $event;
                    }
                  }           
                }    
              }
//echo '<small>'.$eventsql.'<br />('.count($events).')</small>';
              $numqs++;
              if(empty($events) && empty($alldayevents)) {
                $return .= '&nbsp;';
              } else {
                $return .= '<table class="weekfillertable">';
                if(!empty($events)) {
                  $return .= '<tr>';
                  for($hour=0;$hour<24;) {
                     $hourstart = $daystart + ($hour*3600);
                     $hourend = $hourstart + 3600;
                     $hourevents = array();                                               
                        foreach($events as $event) {
                           if(($event->eventstart >= $hourstart) && ($event->eventstart < $hourend)) {
                              $hourevents[] = $event;
                           }
                        }                                                                    
                        if(empty($hourevents)) {
                           $return .= '<td>&nbsp;</td>';
                           $colspan++;
                        } else {
                           $hashourly = 1; 
                           $colspan++;
                           $return .= "\n".'    <td class="weekevent" id="mousehook'.$itemno.'"';
                           if($_GET['updatecal']) {
                             $return .= ' onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')"';
                           } else {
                             $onload .= 'listen(\'mouseover\',\'mousehook'.$itemno.'\',overlayfunc(\''.$itemno.'\',\'event\'));'."\n".
                                        'listen(\'mouseout\',\'mousehook'.$itemno.'\',closefunc(\''.$itemno.'\',\'event\'));'."\n";
                           }
                           $return .= '>'."\n".'       <div id="event'.$itemno.'" class="eventdiv">'.
                                          "\n".'           <div class="title"><strong>'.date("H:i",$hourstart).'</strong></div>'.
                                          "\n".'           <div class="popupcontainer">';
                           foreach($hourevents as $hourevent) {
                               $duration = calcduration($hourevent->eventstart,$hourevent->eventend);
                               $return .= "\n".'               <span class="';
                               switch($_SESSION['IZ_ITEMCOLORS']) {
                                 case 'c':
                                   $return .= 'cat-'.$hourevent->category;
                                   break;
                                 case 'a':
                                   $return .= 'item-'.$hourevent->author;
                                   break;
                                 case 't':
                                   $return .= 'itemtitle';
                                   break;
                               }
                               $return .= '">';
                               if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                                 $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$hourevent->icon].'" class="icon" />';
                               }
                               $return .= '<a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$hourevent->id.'&amp;from=view-month.month-'.$frommonth.'.year-'.$fromyear.'"><strong>'.$hourevent->title."</strong></a></span><br />\n";
                               if(($opt_flags & OPT_CATEGORY) != 0) {
                                 if(empty($_SESSION['eventcats'][$hourevent->category]->name)) {
                                     $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> '.STR_PRIVATE.'<br />'."\n";
                                 } else {
                                     $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> <a href="'.($_SESSION['IZ_REWRITE'] == 'apache' ? $_SESSION['IZ_CALURL'].'category/'.$hourevent->category.'/' : $_SESSION['IZ_CALURL'].'index.php?category='.$hourevent->category).'">'.$_SESSION['eventcats'][$hourevent->category]->name."</a><br />\n";
                                 }
                               }
                               $return .= '               <strong>'.STR_STARTS.'&#58;</strong> '.date("H:i",$hourevent->eventstart).'<br />'."\n";
                               if($duration != '0h 0m') {
                                 $return .= '               <strong>'.STR_DURATION.'&#58;</strong> '.$duration.'<br />';
                               }
                               if(!empty($hourevent->venue)) {
                                 $return .= '<strong>'.STR_VENUE.'&#58;</strong> ';
                                   if($hourevent->linkgoogle == 1) { 
                                     $return .= '<a href="http://maps.google.co.uk/maps?q='.$hourevent->venue.'" title="'.STR_LINKGOOGLE.'"'.(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : '').'>'.$hourevent->venue.'</a>';
                                   } else {
                                     $return .= $hourevent->venue;
                                   }                               
                                   $return .= '<br />';
                               }
                               $return .= "\n               ";
                               if(($hourevent->cust1 != '') && ($_SESSION['cust1'] != 'none')){
                                 $return .= '<strong>'.$_SESSION['cust1'].'&#58;</strong> '.$hourevent->cust1.'<br />';
                               }
                               if(($hourevent->cust2 != '') && ($_SESSION['cust2'] != 'none')){
                                 $return .= '<strong>'.$_SESSION['cust2'].'&#58;</strong> '.$hourevent->cust2.'<br />';
                               }
                               if(($hourevent->cust3 != '') && ($_SESSION['cust3'] != 'none')){
                                 $return .= '<strong>'.$_SESSION['cust3'].'&#58;</strong> '.$hourevent->cust3.'<br />';
                               }
                               if($_SESSION['cpanel'] == 1) {
                                  if(strtolower($hourevent->author) == 'everyone') {
                                    $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.STR_NOTLOGGEDIN.'<br />'."\n               ";
                                  } else {
                                    $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.$hourevent->author.'<br />'."\n               ";
                                  }
                               }
                               if(strlen($hourevent->description)>100) {
                                 $return .= substr(strip_tags($hourevent->description),0,100)."...";
                               } else {
                                 $return .= '<div class="description">'.$hourevent->description.'</div>';
                               }
                               $return .= "\n               ".'<br /><br />';
                           }
                           $return .= "\n           ".'</div>
       </div>
    </td>';
                           $itemno++;                         
                        }
                     $hour++;
                  }
                  $return .= '</tr>';
                } 
                if(!empty($alldayevents)) {
                  $return .= '<tr class="weekallday">'.
                             "\n".'    <td id="mousehook'.$itemno.'" colspan="'.$colspan.'"';
                  if($_GET['updatecal']) {
                    $return .= ' onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')"';
                  } else {
                    $onload .= 'listen(\'mouseover\',\'mousehook'.$itemno.'\',overlayfunc(\''.$itemno.'\',\'event\'));'."\n".
                               'listen(\'mouseout\',\'mousehook'.$itemno.'\',closefunc(\''.$itemno.'\',\'event\'));'."\n";
                  }
                  $return .= ">\n".'       <div id="event'.$itemno.'" class="weekalldaydiv">'."\n           ".'<div class="title"><strong>'.STR_ALLDAYSHORT."</strong></div>\n           ".'<div class="popupcontainer">';
                  foreach($alldayevents as $alldayevent) {
                         $return .= "\n               ".'<span class="';
                         switch($_SESSION['IZ_ITEMCOLORS']) {
                           case 'c':
                             $return .= 'cat-'.$alldayevent->category;
                             break;
                           case 'a':
                             $return .= 'item-'.$alldayevent->author;
                             break;
                           case 't':
                             $return .= 'itemtitle';
                             break;
                         }
                         $return .= '">';
                         if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                           $return .= '<img src="'.$_SESSION['IZ_CALURL'].'/images/icons/'.$icons[$event->icon].'" class="icon" />';
                         }
                         $return .= '<a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=view-month.month-'.$frommonth.'.year-'.$fromyear.'"><strong>'.$alldayevent->title.'</strong></a></span><br />'."\n               ";
                         if(($opt_flags & OPT_CATEGORY) != 0) {
                           if(empty($_SESSION['eventcats'][$alldayevent->category]->name)) {
                             $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> '.STR_PRIVATE.'<br />'."\n               ";
                           } else {
                             if($_SESSION['IZ_REWRITE'] == 'apache') {
                               $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> <a href="'.$_SESSION['IZ_CALURL'].'category/'.$alldayevent->category.'/">'.$_SESSION['eventcats'][$alldayevent->category]->name.'</a><br />'."\n               ";
                             } else {
                               $return .= '<strong>'.STR_CATEGORY.'&#58;</strong> <a href="'.$_SESSION['IZ_CALURL'].'index.php?category='.$alldayevent->category.'">'.$_SESSION['eventcats'][$alldayevent->category]->name.'</a><br />'."\n               ";
                             }
                           }
                         }
                         if(!empty($alldayevent->venue)) {
                           $return .= '<strong>'.STR_VENUE.'&#58;</strong> ';
                             if($alldayevent->linkgoogle == 1) { 
                               $return .= '<a href="http://maps.google.co.uk/maps?q='.$alldayevent->venue.'" title="'.STR_LINKGOOGLE.'"'.(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : '').'>'.$alldayevent->venue.'</a>';
                             } else {
                               $return .= $alldayevent->venue;
                             }                               
                           $return .= '<br />';
                         }
                         if(($alldayevent->cust1 != '') && ($_SESSION['cust1'] != 'none')){
                           $return .= '<strong>'.$_SESSION['cust1'].'&#58;</strong> '.$alldayevent->cust1.'<br />';
                         }
                         if(($alldayevent->cust2 != '') && ($_SESSION['cust2'] != 'none')){
                           $return .= '<strong>'.$_SESSION['cust2'].'&#58;</strong> '.$alldayevent->cust2.'<br />';
                         }
                         if(($alldayevent->cust3 != '') && ($_SESSION['cust3'] != 'none')){
                           $return .= '<strong>'.$_SESSION['cust3'].'&#58;</strong> '.$alldayevent->cust3.'<br />';
                         }
                         if($_SESSION['cpanel'] == 1) {
                            if(strtolower($alldayevent->author) == 'everyone') {
                              $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.STR_NOTLOGGEDIN.'<br />'."\n               ";
                            } else {
                              $return .= '<strong>'.STR_AUTHOR.'&#58;</strong> '.$alldayevent->author.'<br />'."\n               ";
                            }
                         }
                         if(strlen($alldayevent->description)>100) {
                           $return .= substr(strip_tags($alldayevent->description),0,100)."...";
                         } else {
                           $return .= '<div class="description">'.$alldayevent->description.'</div>';
                         }
                         $return .= "\n               ".'<br /><br />';
                  }
                  $return .= "\n           ".'</div>
        </div>
    </td></tr>';
                  $itemno++;
                }
                $return .= '</table>';
              }
              $return .= '</td></tr>'."\n\n\n";
            }
         }
         return $return;
}
/**
* Adds an item to the task list based on $_POST variables
*/
function addtodo() {
      if($_SESSION['edit'] > 0) {
        $id = gen_id();
        if(empty($_POST['addtaskdatedue'])) {
          $duedate = 0;
        } else {
          list($dueday,$duemonth,$dueyear) = explode("/",$_POST['addtaskdatedue']);
          $duedate = mktime(0,0,0,$duemonth,$dueday,$dueyear);
        }
        $cn = substr($_POST['addtaskcategory'],0,3);
        if($cn == 'nct') {
          $category = gen_id();
          $newcatname = substr($_POST['addtaskcategory'],3,strlen($_POST['addtaskcategory']));
          add_category($category,$newcatname,'task','#000000');
          rebuild_cats('task');
        } else {
          $category = $_POST['addtaskcategory'];
        }
        $author = trim($_SESSION['uname']);
        $comments = intval($_POST['addtaskallowcomments']);
        $todo = new todo(new todores($id,$category,0,$duedate,$_POST['addtaskname'],$_POST['addtask'],$author,0,$_POST['addtaskcust1'],$_POST['addtaskcust2'],$_POST['addtaskcust3'],$comments,$_POST['addtaskstatus'],$_POST['addtaskicon']));
        if($todo->insert() == false) {
          echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
          return;
        }
      } else {
        echo '<span>&#35;205&#58; ',ERR_NOPERMISSION,'</span>';
      }
}
/**
* Marks an item as complete/incomplete based on $_REQUEST variables.
*/
function completetodo() {
      if($_REQUEST['status'] == 'complete') {
        $complete = '1';
      } elseif($_REQUEST['status'] == 'incomplete') {
        $complete = '0';
      }
      $todo = new todo(new todores($_REQUEST['id'],'','','','','','','','','','','',''));
      $todo->getdetails();
      if($_SESSION['cpanel'] || (($_SESSION['edit'] == 1) &&
            (strtolower($todo->author) == strtolower($_SESSION['uname']) ||
            (strtolower($todo->author) == 'everyone'))
       || $_SESSION['edit'] == 2)) {
        $todo->complete = $complete;
        $todo->markcomplete();
      } else {
        echo '<span>&#35;206&#58; ',ERR_NOPERMISSION,'</span><br />';
      }
}
/**
* Edits a task based on $_REQUEST variables.
*/
function edittodo() {
       if(empty($_REQUEST['edittaskdatedue'])) {
         $due = 0;
       } else {
         list($day,$month,$year) = explode("/",$_REQUEST['edittaskdatedue']);
         $due = mktime(0,0,0,intval($month),intval($day),intval($year));
       }
       $cn = substr($_REQUEST['edittaskcategory'],0,3);
       if($cn == 'nct') {
         $category = gen_id();
         $newcatname = substr($_REQUEST['edittaskcategory'],3,strlen($_REQUEST['edittaskcategory']));
         add_category($category,$newcatname,'task','#000000');
         rebuild_cats('task');
       } else {
         $category = $_REQUEST['edittaskcategory'];
       }
       $comments = intval($_REQUEST['edittaskallowcomments']);
//var_dump($_GET);       
//echo '1',$_REQUEST['edittaskdesc'];
       $todo = new todo(new todores($_REQUEST['id'],$category,0,$due,str_replace('__SPC__', ' ',$_REQUEST['edittaskname']),$_REQUEST['edittaskdesc'],0,$_REQUEST['complete'],$_REQUEST['edittaskcust1'],$_REQUEST['edittaskcust2'],$_REQUEST['edittaskcust3'],$comments,$_REQUEST['edittaskstatus'],$_REQUEST['edittaskicon']));
       if($_SESSION['edit'] > 0 || $_SESSION['cpanel'] == 1) {
         if($_GET['ajax'] == 1) {
           $todo->ajaxedit();
         } else {
           $todo->edit();
         }
       } else {
         echo '<span>&#35;207&#58; ',ERR_NOPERMISSION,'</span>';
       }
}
/**
* Deletes a task based on $_REQUEST variables.
*/
function deltodo() {
       global $numqs;
       $todo = new todo(new todores($_REQUEST['id'],'','','','','task','','','','','','',''));
       $todo->getdetails();
       if(($_SESSION['delete'] == 1 
            && (strtolower($todo->author) == strtolower($_SESSION['uname']) 
                || (strtolower($todo->author) == 'everyone')
            )
          ) 
          || ($_SESSION['delete'] == 2) 
          || $_SESSION['cpanel'] == 1) {
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $todosql = sprintf("DELETE FROM tasks WHERE id = '%s' LIMIT 1",$dblink->real_escape_string($_REQUEST['id']));
             if(!$dblink->query($todosql)) {
               echo ERR_ERRORTEXT,'&#58; ',mysql_error();
             }
           } else {
             $todosql = sprintf("DELETE FROM tasks WHERE id = '%s' LIMIT 1",mysql_real_escape_string($_REQUEST['id']));
             if(!mysql_query($todosql)) {
               echo ERR_ERRORTEXT,'&#58; ',mysql_error();
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $todosql = sprintf("DELETE FROM \"tasks\" WHERE \"id\" = '%s'",pg_escape_string($_REQUEST['id']));
           if(!pg_query($todosql)) {
             echo ERR_ERRORTEXT,'&#58; ',pg_last_error();
           }
         } elseif(IZ_CALMODE == 'msq') {
           $todosql = sprintf("DELETE FROM tasks WHERE id = '%s'",mssql_escape_string($_REQUEST['id']));
           if(!mssql_query($todosql)) {
             echo ERR_ERRORTEXT,'&#58; ',mssql_get_last_message();
           }
         }
         $numqs++;
      } else {
        echo '<span>&#35;208&#58; ',ERR_NOPERMISSION,'</span>';
      }
}

/**
* Echos the task list.
* @param update 0/1 depending on whether this is the initial load or a reload.
*/
function gettodolist($update) {
    global $onload;
    izsql();
    $todosql = "SELECT * FROM tasks WHERE ((LOWER(author) = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].")".$_SESSION['publicstatus'].") AND due < '".$_SESSION['todospan']['value']."' AND (complete = '0' OR complete = '".$_SESSION['completedtodos']."')".$_SESSION['todocats']['filters']." ORDER BY due ASC";
    if(IZ_CALMODE == 'mysql') {
      if($_SESSION['MYSQLi']) {
        global $dblink;
        $todoqry = $dblink->query($todosql);
        if($todoqry->num_rows > 0) {
           while($sqltodo = $todoqry->fetch_object()) {
             $todo[] = new todo($sqltodo);
           }
        }
      } else {
        $todoqry = mysql_query($todosql);
        if((is_resource($todoqry)) && (mysql_num_rows($todoqry) > 0)) {
           while($sqltodo = mysql_fetch_object($todoqry)) {
             $todo[] = new todo($sqltodo);
           }
        }
      }
    } elseif(IZ_CALMODE == 'postgre') {
       $todosql = "SELECT * FROM \"tasks\" WHERE ((\"author\" = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].")".$_SESSION['publicstatus'].") AND \"due\" < '".$_SESSION['todospan']['value']."' AND (\"complete\" = '0' OR \"complete\" = '".$_SESSION['completedtodos']."')".$_SESSION['todocats']['filters']." ORDER BY \"due\" ASC";
       $todoqry = pg_query($todosql);
       if((is_resource($todoqry)) && (pg_num_rows($todoqry) > 0)) {
          while($sqltodo = pg_fetch_object($todoqry)) {
            $todo[] = new todo($sqltodo);
          }
       }
    } elseif(IZ_CALMODE == 'msq') {
       $todoqry = mssql_query($todosql);
       if((is_resource($todoqry)) && (mssql_num_rows($todoqry) > 0)) {
          while($sqltodo = mssql_fetch_object($todoqry)) {
            $todo[] = new todo($sqltodo);
          }
       }
    }
    $numqs++;
    if($update == 0) { //ie: this is the first time the page has been printed. This div needs to be added because its contents are checked in ajax.js
      echo '<div class="collapsiblebox mediumcontainer" id="todocontainer">',
           '<div class="collapsibletitle"><a class="',($_SESSION['todowithfilters'] == '0' ? 'filters-closed' : 'filters-open'),'" id="toggletodolist" href="#toggle">',STR_TODO,'</a></div>',
           '<div class="collapsiblecontent filters" id="todowithfilters"';
      if($_SESSION['todowithfilters'] == '0') {
        echo ' style="display: none;"';
      }
      echo '>',
           '<div id="taskscontainer"><div id="taskstodo">';
    }
    $onload .= 'listen(\'click\',\'toggletodolist\',toggle(\'todowithfilters\'));'."\n";
    if(!empty($todo)) {
      $u1 = mktime(0,0,0,date("n,j,Y")) - 5 - $_SESSION['IZ_TIMEOFFSET']; // current date
      /* 1-red, 6-green */
      $u2 = $u1 + 129600; //1.5 days
      $u3 = $u2 + 129600;
      $u4 = $u3 + 129600;
      $u5 = $u4 + 129600;
      $u6 = $u5 + 129600;
/* echo date("j n H:i",$u1).'<br>';             
echo date("j n H:i",$u2).'<br>';
echo date("j n H:i",$u3).'<br>';
echo date("j n H:i",$u4).'<br>';
echo date("j n H:i",$u5).'<br>';
echo date("j n H:i",$u6).'<br>'; */
      foreach($todo as $item) {
        if(intval($item->complete) == 1) {
          listtodoitem($item,'complete',$update);
        } elseif($item->due >= $u6) {
          listtodoitem($item,'u6',$update);
        } elseif(($item->due >= $u5) && ($u6 > $item->due)) {
          listtodoitem($item,'u5',$update);
        } elseif(($item->due >= $u4) && ($u5 > $item->due)) {
          listtodoitem($item,'u4',$update);
        } elseif(($item->due >= $u3) && ($u4 > $item->due)) {
          listtodoitem($item,'u3',$update);
        } elseif(($item->due >= $u2) && ($u3 > $item->due)) {
          listtodoitem($item,'u2',$update);
        } elseif(($item->due >= $u1) && ($u2 > $item->due)) {
          listtodoitem($item,'u1',$update);
        } elseif($item->due == 0) {
          listtodoitem($item,'ongoing',$update);
        } else {
          listtodoitem($item,'u1 overdue',$update);
        }
      }
    } else {
      echo STR_NOTASKS;
    }
    if($update == 0) {
      echo '</div></div>'; // end taskstodo,taskscontainer
      if(($_SESSION['IZ_OPT'] & OPT_FILTERS) != 0) {
        echo '<div class="rule">&nbsp;</div>';
        echo gettodofilters('main');
      }
      echo '</div></div>'; // end todowithfilters-collapsiblecontent, todocontainer-collapsiblebox
    }
}
/**
* Echos the form and checkboxes for turning task categories on/off.
*/
function gettodofilters($type) {
        global $secs;
        global $view;
        global $daynum;
        global $monthnum;
        global $yearnum;
        global $onload;
        $opt_flags = $_SESSION['IZ_OPT'];
        if(($opt_flags & OPT_TODO) != 0) {
           echo '<form enctype="multipart/form-data" method="get" name="spanform" action="',$_SESSION['IZ_CALURL'],'index.php" class="filters">';
           if($type == 'main') {
             echo '<h2><a href="#toggle" class="',($_SESSION['todofilters'] == '0' ? 'filters-closed' : 'filters-open'),'" id="toggletodofilters">',STR_FILTERS,'</a></h2>';
             $onload .= 'listen(\'click\',\'toggletodofilters\',toggle(\'todofilters\'));'."\n";
           } else {
             echo '<h2>',STR_TODO,'</h2>';
           }
           echo '<div id="todofilters"';
           if($_SESSION['todofilters'] == '0' && $type == 'main') {
             echo ' style="display: none;"';
           }
           echo '><table width="100%">
             <tr>';
           if(($opt_flags & OPT_CATEGORY) != 0) {
             echo '<td width="50%"><h3>',STR_CATEGORIES,'&#58;</h3></td>'; 
           }
           echo '<td><h3>',STR_DUEIN,'&#58;</h3></td>
             </tr><tr>';
           if(($opt_flags & OPT_CATEGORY) != 0) {
             echo '<td>';
             get_categories('todofilter',$type);
             echo '</td>';
           }
           echo '<td><div class="checks">
                 <label for="oneweek"><input type="radio" name="todospan" value="1week" id="oneweek" ';
          if($_SESSION['todospan']['length'] == '1week') {
            echo 'checked="checked" ';
          }
          echo '/>1 ',STR_WEEK,'</label>
               <label for="onemonth"><input type="radio" name="todospan" value="1month" id="onemonth" ';
          if($_SESSION['todospan']['length'] == '1month') {
            echo 'checked="checked" ';
          }
          echo '/>1 ',STR_MONTH,'</label>
               <label for="sixmonths"><input type="radio" name="todospan" value="6months" id="sixmonths" ';
          if($_SESSION['todospan']['length'] == '6months') {
            echo 'checked="checked" ';
          }
          echo '/>6 ',ucwords(STR_MONTHS),'</label>
                <label for="oneyear"><input type="radio" name="todospan" value="1year" id="oneyear" ';
          if($_SESSION['todospan']['length'] == '1year') {
            echo 'checked="checked" ';
          }
          echo '/>1 ',STR_YEAR,'</label>
                <label for="todospanall"><input type="radio" name="todospan" value="all" id="todospanall" ';
          if(($_SESSION['todospan']['length'] == 'all') || (!isset($_SESSION['todospan']))) {
            echo 'checked="checked" ';
          }
          echo '/>',STR_ALL,'</label>
                <label for="includecompleted"><input type="checkbox" name="includecompleted" value="includecompleted" id="includecompleted"';
          if($_SESSION['completedtodos']) { echo ' checked="checked"'; }
            echo ' />',STR_INCLUDECOMPLETED,'</label>
                 <input type="hidden" name="view" value="',$view,'" /><input type="hidden" name="day" value="',$daynum,'" /><input type="hidden" name="month" value="',$monthnum,'" /><input type="hidden" name="year" value="',$yearnum,'" />
                 </div></td>
                 </tr>
                 </table></div>
                 </form>';
          $onload .= 'listen(\'click\',\'oneweek\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n".
                     'listen(\'click\',\'onemonth\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n".
                     'listen(\'click\',\'sixmonths\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n".
                     'listen(\'click\',\'oneyear\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n".
                     'listen(\'click\',\'todospanall\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n".
                     'listen(\'click\',\'includecompleted\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todospan\',\''.$type.'\'));'."\n";
        }
}
/**
* Lists an item on the task list. Shows the description in a hidden div which is shown onclick
* @param item The Todo object to list
* @param class The class to assign the item to (for the highlight colour)
* @param update 0/1 depending on whether this is the first or a subsequent update
*/
function listtodoitem($item,$class,$update) {
        global $icons;
        // couldn't add listeners due to AJAX
        echo '<span><a class="'.$class.'" href="#" onclick="new Effect.toggle(\'todo'.$item->id.'\',\'slide\', {duration:0.8}); return false;">';
        if(($_SESSION['IZ_OPT'] & OPT_ICON) != 0 && intval($item->icon) != -1) {
          echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$item->icon],'" class="icon" />';
        }
        echo '<strong>'.$item->title.'</strong>';
        if($item->due != 0) {
          echo ' - '.iz_longdate($item->due);
        }
        if($class == 'u1 overdue') {
          echo ' - '.STR_OVERDUE;
        }
        echo '</a></span>
              <div id="todo'.$item->id.'" class="tododiv" style="display: none;"><div class="description">'.$item->description.'<br />';
                if($_SESSION['cpanel'] 
                  || $_SESSION['edit'] == 2
                  || (($_SESSION['edit'] == 1) &&
                      (strtolower($todo->author) == strtolower($_SESSION['uname']) ||
                      (strtolower($todo->author) == 'everyone'))
                 )) {
                  if($item->complete == 0) {
                    echo '<a href="#" onclick="doupdate(\'todo\',\'complete\',\'status\',\'complete\',\'id\',\''.$item->id.'\');" title="',STR_MARKCOMPLETE,'" class="completelink">',STR_MARKCOMPLETE,'</a>',"\n";
                  } else {
                    echo '<a href="#" onclick="doupdate(\'todo\',\'complete\',\'status\',\'incomplete\',\'id\',\''.$item->id.'\');" title="',STR_MARKINCOMPLETE,'" class="incompletelink">',STR_MARKINCOMPLETE,'</a>',"\n";
                  }
                  echo '<a href="#" onclick="showedit(\''.$item->id.'\'';
                  if($update == 0) {
                    echo ',\'firstupdate\'';
                  } else {
                    echo ',\'\subupdate\'';
                  }
                  echo ');" title="',STR_EDITTASK,'" class="editlink">',STR_EDITTASK,'</a>'."\n";
                }
                if($_SESSION['cpanel'] 
                  || $_SESSION['delete'] == 2
                  || (($_SESSION['delete'] == 1) &&
                      (strtolower($todo->author) == strtolower($_SESSION['uname']) ||
                      (strtolower($todo->author) == 'everyone'))
                 )) {
                   if($_SESSION['delete'] > 0) {
                     echo '<a href="#" onclick="doupdate(\'todo\',\'delete\',\'id\',\''.$item->id.'\');" title="',STR_DELETE,'" class="deletelink">',STR_DELETE,'</a>'."\n";
                   }
                 }
    echo '</div></div><br />';   
}
/**
* Shows a list/expanded view of the task list in a table.
*/
function list_todo() {
       global $havetodo;
       global $numqs;
       global $itemno;
       global $onload;
       global $icons;
       $opt_flags = $_SESSION['IZ_OPT'];
       if($_SESSION['canview'] == 1) {
         $todos = array();
         izsql();
         if($_SESSION['cpanel'] == 1) {
           $sql = "SELECT * FROM tasks WHERE 1 ".$_SESSION['todocats']['filters']." AND due < '".$_SESSION['todospan']['value']."' AND (complete = '0' OR complete = '".$_SESSION['completedtodos']."') ORDER BY due ASC";
         } else {
           $sql = "SELECT * FROM tasks WHERE (LOWER(author) = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].")".$_SESSION['publicstatus']."  AND due < '".$_SESSION['todospan']['value']."' AND (complete = '0' OR complete = '".$_SESSION['completedtodos']."')".$_SESSION['todocats']['filters']." ORDER BY due ASC";
         }
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $qry = $dblink->query($sql);
             if($qry->num_rows > 0) {
                while($sqlres = $qry->fetch_object()) {
                  $todos[] = new todo($sqlres);
                }
             }
           } else {
             $qry = mysql_query($sql);
             if((is_resource($qry)) && (mysql_num_rows($qry) > 0)) {
                while($sqlres = mysql_fetch_object($qry)) {
                  $todos[] = new todo($sqlres);
                }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $qry = pg_query($sql);
           if((is_resource($qry)) && (pg_num_rows($qry) > 0)) {
             while($sqlres = pg_fetch_object($qry)) {
               $todos[] = new todo($sqlres);
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $qry = mssql_query($sql);
           if((is_resource($qry)) && (mssql_num_rows($qry) > 0)) {
             while($sqlres = mssql_fetch_object($qry)) {
               $todos[] = new todo($sqlres);
             }
           }
         }
         $numqs++;
         if(!empty($todos)) {
              $havetodo = 1;
              if(($_GET['view'] == 'expanded') || ($_GET['divtype'] == 'expanded')){
                   foreach($todos as $todo) {
                     echo '<table class="expandedview" id="',$todo->id,'"><tr><td colspan="2" class="titleback2"><span class="';
                     switch($_SESSION['IZ_ITEMCOLORS']) {
                       case 'c':
                         echo 'cat-'.$todo->category;
                         break;
                       case 'a':
                         echo 'item-'.$todo->author;
                         break;
                       case 't':
                         echo 'itemtitle';
                         break;
                     }
                     echo '">',$todo->title,'</span>';
                     if(($_SESSION['edit'] == 1 && (strtolower($todo->author) == strtolower($_SESSION['uname']) || (strtolower($todo->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) { echo ' (<a id="edititem',$todo->id,'" href="',$_SESSION['IZ_CALURL'],'index.php?todo=1&amp;act=edittodo&amp;id=',$todo->id,'&amp;from=events&#46;act&#45;manage&#46;view&#45;expanded">',STR_EDIT,'</a>)'; }
                     if(($_SESSION['delete'] == 1 && (strtolower($todo->author) == strtolower($_SESSION['uname']) || (strtolower($todo->author) == 'everyone'))) || ($_SESSION['delete'] == 2)) { echo ' (<a href="javascript:delitem(\'',$todo->id,'\',\'todo\')">',STR_DELETE,'</a>)'; }
                     echo '</td></tr>';
                     if($todo->complete == 1) {
                       echo '<tr><td colspan="2"><span class="infotext">',STR_COMPLETED,'</span></td></tr>';
                     }
                     echo '<tr><td class="formheading">',STR_DATEDUE,'</td><td>';
                     if($todo->due == 0) {
                       echo STR_ONGOING;
                     } else {
                       echo iz_longdate($todo->due);
                     }
                     echo '</td></tr>';
                     if(($opt_flags & OPT_CATEGORY) != 0) {
                         if(empty($_SESSION['todocats'][$todo->category]->name)) {
                             echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td>',STR_PRIVATE,'</td></tr>';
                         } else {
                             echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td><a href="'.($_SESSION['IZ_REWRITE'] == 'apache' ? $_SESSION['IZ_CALURL'].'category/'.$todo->category.'/' : $_SESSION['IZ_CALURL'].'index.php?category='.$todo->category).'">',$_SESSION['todocats'][$todo->category]->name,'</a></td></tr>';
                         }
                     }
                     if($_SESSION['cust1'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust1'],'</td><td>',$todo->cust1,'</td></tr>'; }
                     if($_SESSION['cust2'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust2'],'</td><td>',$todo->cust2,'</td></tr>'; }
                     if($_SESSION['cust3'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust3'],'</td><td>',$todo->cust3,'</td></tr>'; }
                     echo '<tr><td class="formheading">',STR_TASK,'</td><td><div class="description">',$todo->description,'</div></td></tr>',
                          '</table><br />',"\n";
                   }
              } else {
                 echo '<table class="listview" id="todotable">',"\n",'<colgroup><col style="text-align: center; width: 50px;" /><col /><col /><col />';
                 if(($opt_flags & OPT_CATEGORY) != 0) { echo '<col />'; }
                 if($_SESSION['cust1'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust2'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust3'] != 'none') { echo '<col />'; }
                 echo '</colgroup>',"\n",
                      '<thead><tr class="titleback2"><td>',STR_SELECT,'</td><td>',STR_TASKNAME,'</td><td>',STR_DESCRIPTION,'</td><td>',STR_DATEDUE,'</td>';
                 if(($opt_flags & OPT_CATEGORY) != 0) { echo '<td>',STR_CATEGORY,'</td>'; }
                 if($_SESSION['cust1'] != 'none') { echo '<td>',$_SESSION['cust1'],'</td>'; }
                 if($_SESSION['cust2'] != 'none') { echo '<td>',$_SESSION['cust2'],'</td>'; }
                 if($_SESSION['cust3'] != 'none') { echo '<td>',$_SESSION['cust3'],'</td>'; }
                 echo '</tr></thead><tbody>',"\n";
                 $rc = 1;                  
                 foreach($todos as $todo) {
                   if(is_int($rc/2)) {
                     echo '<tr class="even"';                               
                   } else {
                       echo '<tr class="odd"'; 
                   }
                   $rc++;
                   echo ' id="row'.$todo->id.'" onclick="rowselect(\''.$todo->id.'\')"><td><input type="checkbox" id="check'.$todo->id.'" name="todo'.$todo->id.'" value="'.$todo->id.'" onclick="rowselect(\''.$todo->id.'\')" /></td><td onmouseover="overlay(this, \'todo'.$itemno.'\')" onmouseout="overlayclose(\'todo'.$itemno.'\')">';
                   if(($opt_flags & OPT_ICON) != 0 && intval($todo->icon) != -1) {
                     echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$todo->icon],'" class="icon" />';
                   }
                   echo '<span class="';
                   switch($_SESSION['IZ_ITEMCOLORS']) {
                     case 'c':
                       echo 'cat-'.$todo->category;
                       break;
                     case 'a':
                       echo 'item-'.$todo->author;
                       break;
                     case 't':
                       echo 'itemtitle';
                       break;
                   }
                   echo '"><a href="',$_SESSION['IZ_CALURL'],'index.php?todo=1&amp;act=viewtodo&amp;id=',$todo->id,'&amp;from=events&#46;act&#45;manage&#46;view&#45;list">',$todo->title,'</a></span>
                       <div id="todo',$itemno,'" class="masseventdiv">';
                   if(empty($todo->description)) {
                     echo $todo->title;
                   } else {
                     echo '<div class="description">',$todo->description.'</div>';
                   }
                   echo '</div></td><td>';
                   $itemno++;
                   echo '</td><td>';
                   if($todo->due == 0) {
                     echo STR_ONGOING;
                   } else {
                     echo date("Y-m-d",$todo->due);
                   }
                   echo '</td>';
                   if(($opt_flags & OPT_CATEGORY) != 0) {
                     if(empty($_SESSION['todocats'][$todo->category]->name)) {
                       echo '<td>',STR_PRIVATE,'</td>';
                     } else {
                       if($_SESSION['IZ_REWRITE'] == 'apache') {
                         echo '<td><a href="',$_SESSION['IZ_CALURL'],'category/',$todo->category,'/">',$_SESSION['todocats'][$todo->category]->name,'</a></td>';
                       } else {
                         echo '<td><a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category=',$todo->category,'">',$_SESSION['todocats'][$todo->category]->name,'</a></td>';
                       }
                     }
                   }
                   if($_SESSION['cust1'] != 'none') { echo '<td>',$todo->cust1,'</td>'; }
                   if($_SESSION['cust2'] != 'none') { echo '<td>',$todo->cust2,'</td>'; }
                   if($_SESSION['cust3'] != 'none') { echo '<td>',$todo->cust3,'</td>'; }
                   echo '</tr>',"\n";
                 }  
                 echo '</tbody></table>';                
           }
         } else {
           echo '<h4 class="calwrappertext">',STR_NOTASKS,'</h4>';
         }
       } else {
                echo '<span>&#35;209&#58; ',ERR_NOPERMISSION,'</span>';
       }
}
/**
* Shows the links to the next/previous page in event manager
*/
function getpagination($numevents,$startnum) {
       izsql();
       if($_GET['view'] == 'expanded') {
         $view = 'expanded';
       } else {
         $view = 'list';
       }
       $pagenum = 1;
       $numlisted = 0;
       echo '<span class="pagelist calwrappertext"><strong>',STR_PAGINATION,'&#58; </strong>';
       while($numlisted<$numevents) {
         if(($numlisted<=$startnum) && ($startnum<($numlisted+$_SESSION['pageafter']))) {
           echo '<strong>&#91;',$pagenum,'&#93;&nbsp;</strong>';
         } else {
           echo '<a href="',$_SESSION['IZ_CALURL'];
           if($_SESSION['IZ_REWRITE'] == 'apache') {
             echo 'manage/',$view,'/',$numlisted,'/';
           } else {
             echo 'index.php?events=1&amp;act=manage&amp;view=',$view,'&amp;start=',$numlisted;
           }
           echo '">',$pagenum,'</a>&nbsp;';
         }
         $numlisted = $numlisted+$_SESSION['pageafter'];
         $pagenum++;
       }
       echo '</span>';
}
/**
* Shows a list/expanded view of the calendar in a table.
*/
function list_events() {
       global $numqs;
       global $haveevents;
       global $itemno;
       global $onload;
       global $icons;
       $opt_flags = $_SESSION['IZ_OPT'];
       if($_SESSION['canview'] == 1) {
         $events = array();
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             if($_SESSION['cpanel'] == 1) {
               $eventsql = "SELECT * FROM events WHERE 1".$_SESSION['eventcats']['filters'].' ORDER BY eventstart DESC';
             } else {
               $eventsql = "SELECT * FROM events WHERE ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters'].' ORDER BY eventstart DESC';
             }
             $eventres = $dblink->query($eventsql);
             if($eventres->num_rows > 0) {
                while($sqlevent = $eventres->fetch_object()) {
                  $events[] = new event($sqlevent);
                }
             }
           } else {
             if($_SESSION['cpanel'] == 1) {
               $eventsql = "SELECT * FROM events WHERE 1".$_SESSION['eventcats']['filters'].' ORDER BY eventstart DESC';
             } else {
               $eventsql = "SELECT * FROM events WHERE ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters'].' ORDER BY eventstart DESC';
             }
             $eventqry = mysql_query($eventsql);
             if((is_resource($eventqry)) && (mysql_num_rows($eventqry) > 0)) {
                while($sqlevent = mysql_fetch_object($eventqry)) {
                  $events[] = new event($sqlevent);
                }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM \"events\" WHERE 1 ".$_SESSION['eventcats']['filters']." ORDER BY \"eventstart\"";
           } else {
             $eventsql = "SELECT * FROM \"events\" WHERE ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters']." ORDER BY \"eventstart\"";
           }
           $eventqry = pg_query($eventsql);
           if((is_resource($eventqry)) && (pg_num_rows($eventqry) > 0)) {
              while($sqlevent = pg_fetch_object($eventqry)) {
                $events[] = new event($sqlevent);
              }
           }
         } elseif(IZ_CALMODE == 'msq') {
           if($_SESSION['cpanel'] == 1) {
             if($limstart == 0) { $limstart = 1; } //to prevent division by zero
               $eventsql = "SELECT TOP ".$_SESSION['pageafter']." * FROM (SELECT TOP ".(($_SESSION['pageafter']/$limstart) * $_SESSION['pageafter'])." * FROM events AS T1 WHERE 1 ".$_SESSION['eventcats']['filters']." ORDER BY eventstart DESC) AS T2 ORDER BY eventstart ASC";
           } else {
               $eventsql = "SELECT TOP ".$_SESSION['pageafter']." * FROM (SELECT TOP ".(($_SESSION['pageafter']/$limstart) * $_SESSION['pageafter'])." * FROM events AS T1 WHERE ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")".$_SESSION['eventcats']['filters']." ORDER BY eventstart DESC) AS T2 ORDER BY eventstart ASC";
           }
           $eventqry = mssql_query($eventsql);
           if((is_resource($eventqry)) && (mssql_num_rows($eventqry) > 0)) {
              while($sqlevent = mssql_fetch_object($eventqry)) {
                $events[] = new event($sqlevent);
              }
           }
         }
         $numqs++;
         $numevents = count($events);
         $numlisted = 0;
         if(isset($_GET['start'])) {
           $limstart = $_GET['start'];
         } else {
           $limstart = 0;
         }
         if($limstart+$_SESSION['pageafter'] <= $numevents) {
           $stopat = $limstart + $_SESSION['pageafter'];
         } else {
           $stopat = $numevents;
         }
         if($limstart < $numevents) {
             $haveevents = 1;
             if(($_GET['view'] == 'expanded') || ($_GET['divtype'] == 'expanded')) {
                 for($i=$limstart;$i<$stopat;$i++) {
                     $event = $events[$i];
                     echo '<table class="expandedview" id="',$event->id,'"><tr><td colspan="2" class="titleback2">';
                     if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                       echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$event->icon],'" class="icon" />';
                     }
                     echo '<span class="';
                     switch($_SESSION['IZ_ITEMCOLORS']) {
                       case 'c':
                         echo 'cat-'.$event->category;
                         break;
                       case 'a':
                         echo 'item-'.$event->author;
                         break;
                       case 't':
                         echo 'itemtitle';
                         break;
                     }
                     echo '">',$event->title,'</span>';
                     if(($_SESSION['edit'] == 1 && (strtolower($event->author) == strtolower($_SESSION['uname']) || (strtolower($event->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) { echo ' (<a href="',$_SESSION['IZ_CALURL'],'index.php?events=1&amp;act=editevent&amp;event=',$event->id,'&amp;from=events&#46;act&#45;manage&#46;view&#45;expanded">',STR_EDIT,'</a>)'; }
                     if(($_SESSION['delete'] == 1 && (strtolower($event->author) == strtolower($_SESSION['uname']) || (strtolower($event->author) == 'everyone'))) || ($_SESSION['delete'] == 2)) { echo ' (<a href="javascript:delitem(\'',$event->id,'\',\'event\')">',STR_DELETE,'</a>)'; }
                     echo '</td></tr>';
                     if(($opt_flags & OPT_ENDDATE) != 0) {
                       if($event->allday == 1) {
                         echo '<tr><td colspan="2"><span class="infotext">',calcduration($event->eventstart,$event->eventend,true,'ext'),'</span></td></tr>';
                         echo '<tr><td class="formheading">',STR_STARTS,'</td><td>',iz_longdate($event->eventstart),'</td></tr>';
                       } else {
                         echo '<tr><td class="formheading">',STR_STARTS,'</td><td>',iz_longdatehours($event->eventstart),'</td></tr>';
                         echo '<tr><td class="formheading">',STR_ENDS,'</td><td>',iz_longdatehours($event->eventend),'</td></tr>';
                       }
                     } else {
                         echo '<tr><td class="formheading">',STR_DATE,'</td><td>',iz_longdatehours($event->eventstart),'</td></tr>';
                     }
                     if(($opt_flags & OPT_VENUE) != 0) {
                       echo '<tr><td class="formheading">',STR_VENUE,'</td><td>';
                       if(($event->linkgoogle == 1) && (($opt_flags & OPT_GOOGLE) != 0)) { 
                         echo '<a href="http://maps.google.co.uk/maps?q=',$event->venue,'" title="',STR_LINKGOOGLE,'"',(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : ''),'>',$event->venue,'</a>';
                       } else {
                         echo $event->venue;
                       }
                       echo '</td></tr>';
                     }                     
                     if(($opt_flags & OPT_CATEGORY) != 0) {
                       if(empty($_SESSION['eventcats'][$event->category]->name)) {
                         echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td>',STR_PRIVATE,'</td></tr>';
                       } else {
                         echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td><a href="',$_SESSION['IZ_CALURL'],($_SESSION['IZ_REWRITE'] == 'apache' ? 'category/'.$event->category.'/' : 'index.php?category='.$event->category).'">',$_SESSION['eventcats'][$event->category]->name,'</a></td></tr>';
                       }
                     }
                     if($_SESSION['cust1'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust1'],'</td><td>',$event->cust1,'</td></tr>'; }
                     if($_SESSION['cust2'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust2'],'</td><td>',$event->cust2,'</td></tr>'; }
                     if($_SESSION['cust3'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust3'],'</td><td>',$event->cust3,'</td></tr>'; }
                     echo '<tr><td class="formheading">',STR_DESCRIPTION,'</td><td><div class="description">',$event->description,'</div></td></tr></table><br />',"\n";
                     $numlisted++;
                   }
              } else {
                 echo '<table class="listview" id="listtable"><colgroup><col style="text-align: center; width: 50px;" /><col /><col />';
                 if(($opt_flags & OPT_ENDDATE) != 0) { echo '<col /><col />'; }
                 if(($opt_flags & OPT_VENUE) != 0) { echo '<col />'; }
                 if(($opt_flags & OPT_CATEGORY) != 0) { echo '<col />'; }
                 if($_SESSION['cust1'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust2'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust3'] != 'none') { echo '<col />'; }
                 echo '</colgroup>',
                      '<thead><tr class="titleback2"><td>',STR_SELECT,'</td><td>',STR_NAME,'</td>';
                 if(($opt_flags & OPT_ENDDATE) != 0) {
                   echo '<td>',STR_STARTS,'</td><td>',STR_ENDS,'</td><td>',STR_DURATION,'</td>';
                 } else {
                   echo '<td>',STR_DATE,'</td>';
                 }
                 if(($opt_flags & OPT_VENUE) != 0) { echo '<td>',STR_VENUE,'</td>'; }
                 if(($opt_flags & OPT_CATEGORY) != 0) { echo '<td>',STR_CATEGORY,'</td>'; }
                 if($_SESSION['cust1'] != 'none') { echo '<td>',$_SESSION['cust1'],'</td>'; }
                 if($_SESSION['cust2'] != 'none') { echo '<td>',$_SESSION['cust2'],'</td>'; }
                 if($_SESSION['cust3'] != 'none') { echo '<td>',$_SESSION['cust3'],'</td>'; }
                 echo '</tr></thead><tbody>',"\n";
                 $rc = 1;                  
                 for($i=$limstart;$i<$stopat;$i++) {
                   $event = $events[$i];
                   $itemno++;
                   if(is_int($rc/2)) { 
                     echo '<tr class="even"';
                   } else { 
                       echo '<tr class="odd"';
                   }
                   echo ' id="row'.$event->id.'" onclick="rowselect(\''.$event->id.'\')">';                   
                   $rc++;
                   echo '<td><input type="checkbox" id="check'.$event->id.'" name="even'.$event->id.'" value="'.$event->id.'" onclick="rowselect(\''.$event->id.'\')" /></td>
                         <td onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')">';
                   if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                     echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$event->icon],'" class="icon" />';
                   }
                   echo '<span class="';
                   switch($_SESSION['IZ_ITEMCOLORS']) {
                     case 'c':
                       echo 'cat-'.$event->category;
                       break;
                     case 'a':
                       echo 'item-'.$event->author;
                       break;
                     case 't':
                       echo 'itemtitle';
                       break;
                   }
                   echo '"><a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=events&#46;act&#45;manage&#46;view&#45;list">'.$event->title.'</a></span>
                         <div id="event'.$itemno.'" class="masseventdiv">';
                         if(empty($event->description)) {
                            echo $event->title;
                          } else {
                            echo '<div class="description">',$event->description.'</div>';
                          }
                   echo '</div></td>';
                   if(($opt_flags & OPT_ENDDATE) != 0) {
                     echo '<td>',date("Y-m-d",$event->eventstart),'</td><td>',date("Y-m-d",$event->eventend),'</td><td>';
                     if($event->allday == 1) {
                          echo calcduration($event->eventstart,$event->eventend,true,STR_ALLDAYSHORT);
                     } else {
                          echo calcduration($event->eventstart,$event->eventend);
                     }
                     echo '</td>';
                   } else {
                     echo '<td>',date("Y-m-d",$event->eventstart),'</td>';
                   }
                   if(($opt_flags & OPT_VENUE) != 0) {
                     if($event->linkgoogle == 1) { 
                       echo '<td><a href="http://maps.google.co.uk/maps?q=',$event->venue,'" title="',STR_LINKGOOGLE,'"',(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : ''),'>',$event->venue,'</a></td>';
                     } else {
                       echo '<td>',$event->venue,'</td>';
                     }
                   }
                   if(($opt_flags & OPT_CATEGORY) != 0) {
                     if(!empty($_SESSION['eventcats'][$event->category]->name)) {
                       if($_SESSION['IZ_REWRITE'] == 'apache') {
                         echo '<td><a href="',$_SESSION['IZ_CALURL'],'category/',$event->category,'/">',$_SESSION['eventcats'][$event->category]->name,'</a></td>';
                       } else {
                         echo '<td><a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category=',$event->category,'">',$_SESSION['eventcats'][$event->category]->name,'</a></td>';
                       }
                     } else {
                         echo '<td>',STR_PRIVATE,'</td>';
                     }
                   }
                   if($_SESSION['cust1'] != 'none') { echo '<td>',$event->cust1,'</td>'; }
                   if($_SESSION['cust2'] != 'none') { echo '<td>',$event->cust2,'</td>'; }
                   if($_SESSION['cust3'] != 'none') { echo '<td>',$event->cust3,'</td>'; }
                   echo "</tr>\n";
                   $numlisted++;
                 }
                 echo '</tbody></table><br />'.$limstart.' - '.$stopat.' '.STR_OF.' '.$numevents.'<br /><br />';
           }
           getpagination($numevents,$limstart);
         } else {
           echo '<h4 class="calwrappertext">',STR_NOEVENTSFOUND,'</h4>';
         }
       } else {
         echo '<span>&#35;210&#58; ',ERR_NOPERMISSION,'</span>';
       }
}
/**
* Shows all items/tasks in the specified category
* @param rawcat The ID of the category to show
*/
function showcategory($rawcat) {
       global $numqs;
       global $haveevents;
       global $onload;
       global $itemno;
       global $icons;
       $opt_flags = $_SESSION['IZ_OPT'];
       if($_SESSION['canview'] == 1) {
         $events = array();
         $todos = array();
         if(array_key_exists($_GET['category'],$_SESSION['eventcats'])) {
           $catname = $_SESSION['eventcats'][$_GET['category']]->name;
         } elseif(array_key_exists($_GET['category'],$_SESSION['todocats'])) {
           $catname = $_SESSION['todocats'][$_GET['category']]->name;
         } else {
           $catname = ' &#187; '.STR_VIEWINGCATEGORY;
         }
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $category = $dblink->real_escape_string($rawcat);
             if($_SESSION['cpanel'] == 1) {
               $eventsql = "SELECT * FROM events WHERE category = '".$category."' ORDER BY title";
               $todosql = "SELECT * FROM tasks WHERE category = '".$category."' ORDER BY due";
             } else {
               $eventsql = "SELECT * FROM events WHERE category = '".$category."' AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].") ORDER BY title";
               $todosql = "SELECT * FROM tasks WHERE category = '".$category."' AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].")".$_SESSION['publicstatus'].") ORDER BY due ASC";
             }
             $eventres = $dblink->query($eventsql);
               while($sqlevent = $eventres->fetch_object()) {  
                 $events[] = new event($sqlevent);
               }
             $eventres->close();
             if(($opt_flags & OPT_TODO) != 0) {
               $todores = $dblink->query($todosql);
                 while($sqlres = $todores->fetch_object()) {
                   $todos[] = new todo($sqlres);
                 }
             }
//echo 'ddd'.$todosql;
           } else {
             $category = mysql_real_escape_string($rawcat);
             if($_SESSION['cpanel'] == 1) {
               $eventsql = "SELECT * FROM events WHERE category = '".$category."' ORDER BY title";
               $todosql = "SELECT * FROM tasks WHERE category = '".$category."' ORDER BY due";
             } else {
               $eventsql = "SELECT * FROM events WHERE category = '".$category."' AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].") ORDER BY title";
               $todosql = "SELECT * FROM tasks WHERE category = '".$category."' AND (LOWER(author) = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].") ORDER BY due ASC";
             }
             $eventqry = mysql_query($eventsql);
             if(is_resource($eventqry)) {
               while($sqlevent = mysql_fetch_object($eventqry)) {  
                 $events[] = new event($sqlevent);
               }
             }
             if(($opt_flags & OPT_TODO) != 0) {
               $todoqry = mysql_query($todosql);
               if((is_resource($todoqry)) && (mysql_num_rows($todoqry) > 0)) {
                 while($sqlres = mysql_fetch_object($todoqry)) {
                   $todos[] = new todo($sqlres);
                 }
               }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $category = pg_escape_string($rawcat);
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM \"events\" WHERE \"category\" = '".$category."' ORDER BY \"title\"";
             $todosql = "SELECT * FROM \"tasks\" WHERE \"category\" = '".$category."' ORDER BY \"due\"";
           } else {
             $eventsql = "SELECT * FROM \"events\" WHERE \"category\" = '".$category."' AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].") ORDER BY \"title\"";
             $todosql = "SELECT * FROM \"tasks\" WHERE \"category\" = '".$category."' AND (\"author\" = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].") ORDER BY \"due\" ASC";
           }
           $eventqry = pg_query($eventsql);
           if(is_resource($eventqry)) {
             while($sqlevent = pg_fetch_object($eventqry)) {  
               $events[] = new event($sqlevent);
             }
           }
           if(($opt_flags & OPT_TODO) != 0) {
             $todoqry = pg_query($todosql);
             if((is_resource($todoqry)) && (pg_num_rows($todoqry) > 0)) {
               while($sqlres = pg_fetch_object($todoqry)) {
                 $todos[] = new todo($sqlres);
               }
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $category = mssql_escape_string($rawcat);
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM events WHERE category = '".$category."' ORDER BY title";
             $todosql = "SELECT * FROM tasks WHERE category = '".$category."' ORDER BY due";
           } else {
             $eventsql = "SELECT * FROM events WHERE category = '".$category."' AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].") ORDER BY title";
             $todosql = "SELECT * FROM tasks WHERE category = '".$category."' AND (LOWER(author) = '".strtolower($_SESSION['uname'])."'".$_SESSION['authoreveryone'].") ORDER BY due ASC";
           }
//echo '<br><br>'.$eventsql.'<br><br>';
           $eventqry = mssql_query($eventsql);
           if(is_resource($eventqry)) {
             while($sqlevent = mssql_fetch_object($eventqry)) {  
               $events[] = new event($sqlevent);
             }
           }
           if(($opt_flags & OPT_TODO) != 0) {
             $todoqry = mssql_query($todosql);
             if((is_resource($todoqry)) && (mssql_num_rows($todoqry) > 0)) {
               while($sqlres = mssql_fetch_object($todoqry)) {
                 $todos[] = new todo($sqlres);
               }
             }
           }
         }
         $numqs++;
         if(!empty($events)) {
              $haveevents = 1;
              if(($_GET['view'] == 'expanded') || ($_GET['divtype'] == 'expanded')) {
                if($_SESSION['IZ_REWRITE'] == 'apache') {
                  echo '<h3 class="calwrappertext"><strong>',STR_VIEW,'&#58;</strong> <a href="',$_SESSION['IZ_CALURL'],'category/',$rawcat,'/list/">',STR_VIEWLIST,'</a> &#58;&#58; <a href="',$_SESSION['IZ_CALURL'],'category/',$rawcat,'/expanded/">',STR_VIEWEXPAND,'</a></h3>';
                } else {
                  echo '<h3 class="calwrappertext"><strong>',STR_VIEW,'&#58;</strong> <a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category&#61;',$rawcat,'&#38;view&#61;list">',STR_VIEWLIST,'</a> &#58;&#58; <a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category&#61;',$rawcat,'&#38;view&#61;expanded">',STR_VIEWEXPAND,'</a></h3>';
                }
                echo '<h2 class="calwrappertext">',STR_VIEWINGCATEGORY,'&#58; '.$catname.'</h2>';
                foreach($events as $event) {
                  echo '<table id="',$event->id,'" class="expandedview"><tr><td colspan="2" class="titleback2">';
                  if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                    echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$event->icon],'" class="icon" />';
                  }
                  echo '<span class="';
                  switch($_SESSION['IZ_ITEMCOLORS']) {
                    case 'c':
                      echo 'cat-'.$event->category;
                      break;
                    case 'a':
                      echo 'item-'.$event->author;
                      break;
                    case 't':
                      echo 'itemtitle';
                      break;
                  }
                  echo '">',$event->title,'</span>';
                  if(($_SESSION['edit'] == 1 && (strtolower($event->author) == strtolower($_SESSION['uname']) || (strtolower($event->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) { echo ' (<a href="',$_SESSION['IZ_CALURL'],'index.php?events=1&amp;act=editevent&amp;event=',$event->id,'&amp;from=events&#46;act&#45;manage&#46;view&#45;expanded">',STR_EDIT,'</a>)'; }
                  if(($_SESSION['delete'] == 1 && (strtolower($event->author) == strtolower($_SESSION['uname']) || (strtolower($event->author) == 'everyone'))) || ($_SESSION['delete'] == 2)) { echo ' (<a href="javascript:delitem(\'',$event->id,'\',\'event\')">',STR_DELETE,'</a>)'; }
                  echo '</td></tr>';
                  if(($opt_flags & OPT_ENDDATE) != 0) {
                    if($event->allday == 1) {
                      echo '<tr><td colspan="2"><span class="infotext">',calcduration($event->eventstart,$event->eventend,true,'ext'),'</span></td></tr>';
                      echo '<tr><td class="formheading">',STR_STARTS,'</td><td>',iz_longdate($event->eventstart),'</td></tr>';
                    } else {
                      echo '<tr><td class="formheading">',STR_STARTS,'</td><td>',iz_longdatehours($event->eventstart),'</td></tr>';
                      echo '<tr><td class="formheading">',STR_ENDS,'</td><td>',iz_longdatehours($event->eventend),'</td></tr>';
                    }
                  } else {
                     echo '<tr><td class="formheading">',STR_DATE,'</td><td>',iz_longdatehours($event->eventstart),'</td></tr>';
                  }
                  if(($opt_flags & OPT_VENUE) != 0) {
                    echo '<tr><td class="formheading">',STR_VENUE,'</td><td>';
                    if($event->linkgoogle == 1) {
                      echo '<a href="http://maps.google.co.uk/maps?q=',$event->venue,'" title="',STR_LINKGOOGLE,'"',(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : ''),'>',$event->venue,'</a>';
                    } else {
                      echo $event->venue;
                    }
                    echo '</td></tr>';
                  }
                  if($_SESSION['cust1'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust1'],'</td><td>',$event->cust1,'</td></tr>'; }
                  if($_SESSION['cust2'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust2'],'</td><td>',$event->cust2,'</td></tr>'; }
                  if($_SESSION['cust3'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust3'],'</td><td>',$event->cust3,'</td></tr>'; }
                  if($_SESSION['cpanel'] == 1) {
                    if(strtolower($event->author) == 'everyone') {
                      echo '<tr><td class="formheading">',STR_AUTHOR,'</td><td>',STR_NOTLOGGEDIN,'</td></tr>';
                    } else {
                      echo '<tr><td class="formheading">',STR_AUTHOR,'</td><td>',$event->author,'</td></tr>';
                    }
                  }
                  echo '<tr><td class="formheading">',STR_DESCRIPTION,'</td><td><div class="description">',$event->description,'</div></td></tr></table><br />';
                }
              } else {
                 getmassactions();
                 if($_SESSION['IZ_REWRITE'] == 'apache') {
                   echo '<h3 class="calwrappertext"><strong>',STR_VIEW,'&#58;</strong> <a href="',$_SESSION['IZ_CALURL'],'category/',$rawcat,'/list/">',STR_VIEWLIST,'</a> &#58;&#58; <a href="',$_SESSION['IZ_CALURL'],'category/',$rawcat,'/expanded/">',STR_VIEWEXPAND,'</a></h3>';
                 } else {
                   echo '<h3 class="calwrappertext"><strong>',STR_VIEW,'&#58;</strong> <a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category&#61;',$rawcat,'&#38;view&#61;list">',STR_VIEWLIST,'</a> &#58;&#58; <a href="',$_SESSION['IZ_CALURL'],'index.php&#63;category&#61;',$rawcat,'&#38;view&#61;expanded">',STR_VIEWEXPAND,'</a></h3>';
                 }
                 echo '<h2 class="calwrappertext">',STR_VIEWINGCATEGORY,'&#58; '.$catname.'</h2>
                       <div id="listevents"><table class="listview" id="listtable"><colgroup><col style="text-align: center; width: 50px;" /><col /><col />';
                 if(($opt_flags & OPT_ENDDATE) != 0) { echo '<col /><col />'; }
                 if(($opt_flags & OPT_VENUE) != 0) { echo '<col />'; }
                 echo '</colgroup>
                        <thead><tr class="titleback2"><td>',STR_SELECT,'</td>
                        <td>',STR_NAME,'</td>';
                 if(($opt_flags & OPT_ENDDATE) != 0) { 
                   echo '<td>',STR_STARTS,'</td><td>',STR_ENDS,'</td><td>',STR_DURATION,'</td>';
                 } else {
                   echo '<td>',STR_DATE,'</td>';
                 }
                 if(($opt_flags & OPT_VENUE) != 0) { echo '<td>',STR_VENUE,'</td>'; }
                 if($_SESSION['cust1'] != 'none') { echo '<td>',$_SESSION['cust1'],'</td>'; }
                 if($_SESSION['cust2'] != 'none') { echo '<td>',$_SESSION['cust2'],'</td>'; }
                 if($_SESSION['cust3'] != 'none') { echo '<td>',$_SESSION['cust3'],'</td>'; }
                 echo '</tr></thead><tbody>';
                 $rc = 1;                  
                 foreach($events as $event) {
                   if(is_int($rc/2)) { 
                     echo '<tr class="even"';                               
                   } else { 
                       echo '<tr class="odd"'; 
                   }
                   echo ' id="row'.$event->id.'" onclick="rowselect(\''.$event->id.'\')">';
                   $rc++;
                   echo '<td><input type="checkbox" id="check'.$event->id.'" name="even'.$event->id.'" value="'.$event->id.'" onclick="rowselect(\''.$event->id.'\')" /></td>';
                   echo '<td onmouseover="overlay(this, \'event'.$itemno.'\')" onmouseout="overlayclose(\'event'.$itemno.'\')"><a href="'.$_SESSION['IZ_CALURL'].'index.php?events=1&amp;act=viewevent&amp;event='.$event->id.'&amp;from=events&#46;act&#45;manage&#46;view&#45;list">'.$event->title.'</a>
                         <div id="event'.$itemno.'" class="masseventdiv">';
                         if(empty($event->description)) {
                            echo $event->title;
                          } else {
                            echo '<div class="description">',$event->description,'</div>';
                          }
                   echo '</div></td>';
                   if(($opt_flags & OPT_ENDDATE) != 0) {
                     echo '<td>',date("Y-m-d",$event->eventstart),'</td><td>',date("Y-m-d",$event->eventend),'</td><td>';
                     if($event->allday == 1) {
                       echo calcduration($event->eventstart,$event->eventend,true,STR_ALLDAYSHORT);
                     } else {
                       echo calcduration($event->eventstart,$event->eventend);
                     }
                     echo '</td>';
                   } else {
                     echo '<td>',date("Y-m-d",$event->eventstart),'</td>';
                   }
                   if(($opt_flags & OPT_VENUE) != 0) {
                     if($event->linkgoogle == 1) { 
                       echo '<td><a href="http://maps.google.co.uk/maps?q=',$event->venue,'" title="',STR_LINKGOOGLE,'"',(($opt_flags & OPT_GOOGLENEWWINDOW) != 0 ? ' target="_blank"' : ''),'>',$event->venue,'</a></td>';
                     } else {
                       echo '<td>',$event->venue,'</td>';
                     }
               }
               if($_SESSION['cust1'] != 'none') { echo '<td>',$event->cust1,'</td>'; }
               if($_SESSION['cust2'] != 'none') { echo '<td>',$event->cust2,'</td>'; }
               if($_SESSION['cust3'] != 'none') { echo '<td>',$event->cust3,'</td>'; }
               echo '</tr>';
               $itemno++;
             }         
             echo '</tbody></table></div><input type="hidden" name="from" value="events-1.act-manage.view-list" />';
             echo '<input type="hidden" name="events" value="events" /></form>';
           }
         }
         if(!empty($todos)) {
              $haveevents = 1;
              if(($_GET['view'] == 'expanded') || ($_GET['divtype'] == 'expanded')){
                   foreach($todos as $todo) {
                     echo '<table class="expandedview" id="',$todo->id,'"><tr><td colspan="2" class="titleback2">';
                     if(($opt_flags & OPT_ICON) != 0 && intval($event->icon) != -1) {
                       echo '<img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icons[$event->icon],'" class="icon" />';
                     }
                     echo '<span class="';
                     switch($_SESSION['IZ_ITEMCOLORS']) {
                       case 'c':
                         echo 'cat-'.$todo->category;
                         break;
                       case 'a':
                         echo 'item-'.$todo->author;
                         break;
                       case 't':
                         echo 'itemtitle';
                         break;
                     }
                     echo '">',$todo->title,'</span>';
                     if(($_SESSION['edit'] == 1 && (strtolower($todo->author) == strtolower($_SESSION['uname']) || (strtolower($todo->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) { echo ' (<a href="',$_SESSION['IZ_CALURL'],'index.php?todo=1&amp;act=edittodo&amp;id=',$todo->id,'&amp;from=events&#46;act&#45;manage&#46;view&#45;expanded">',STR_EDIT,'</a>)'; }
                     if(($_SESSION['delete'] == 1 && (strtolower($todo->author) == strtolower($_SESSION['uname']) || (strtolower($todo->author) == 'everyone'))) || ($_SESSION['delete'] == 2)) { echo ' (<a href="javascript:delitem(\'',$todo->id,'\',\'todo\')">',STR_DELETE,'</a>)'; }
                     echo '</td></tr>';
                     if($todo->complete == 1) {
                       echo '<tr><td colspan="2"><span class="infotext">',STR_COMPLETED,'</span></td></tr>';
                     }
                     echo '<tr><td class="formheading">',STR_DATEDUE,'</td><td>';
                     if($todo->due == 0) {
                       echo STR_ONGOING;
                     } else {
                       echo iz_longdate($todo->due);
                     }
                     echo '</td></tr>';
                     if(empty($_SESSION['todocats'][$todo->category]->name)) {
                       echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td>',STR_PRIVATE,'</td></tr>';
                     } else {
                       echo '<tr><td class="formheading">',STR_CATEGORY,'</td><td><a href="',$_SESSION['IZ_CALURL'],($_SESSION['IZ_REWRITE'] == 'apache' ? 'category/'.$todo->category.'/' : 'index.php?category='.$todo->category).'">',$_SESSION['todocats'][$todo->category]->name,'</a></td></tr>';
                     }
                     if($_SESSION['cust1'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust1'],'</td><td>',$todo->cust1,'</td></tr>'; }
                     if($_SESSION['cust2'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust2'],'</td><td>',$todo->cust2,'</td></tr>'; }
                     if($_SESSION['cust3'] != 'none') { echo '<tr><td class="formheading">',$_SESSION['cust3'],'</td><td>',$todo->cust3,'</td></tr>'; }
                     echo '<tr><td class="formheading">',STR_TASK,'</td><td><div class="description">',$todo->description,'</div></td></tr>
                           </table><br />';
                   }
              } else {
                 getmassactions();
                 echo '<h2 class="calwrappertext">',STR_VIEWINGCATEGORY,'&#58; ',$catname,'</h2>              
                       <table class="listview" id="todotable"><colgroup><col style="text-align: center; width: 50px;" /><col /><col /><col /><col />';
                 if($_SESSION['cust1'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust2'] != 'none') { echo '<col />'; }
                 if($_SESSION['cust3'] != 'none') { echo '<col />'; }
                 echo '</colgroup>
                       <thead><tr class="titleback2"><td>',STR_SELECT,'</td><td>',STR_TASKNAME,'</td><td>',STR_DESCRIPTION,'</td><td>',STR_DATEDUE,'</td><td>',STR_CATEGORY,'</td>';
                 if($_SESSION['cust1'] != 'none') { echo '<td>',$_SESSION['cust1'],'</td>'; }
                 if($_SESSION['cust2'] != 'none') { echo '<td>',$_SESSION['cust2'],'</td>'; }
                 if($_SESSION['cust3'] != 'none') { echo '<td>',$_SESSION['cust3'],'</td>'; }
                 echo '</tr></thead><tbody>';
                 $rc = 1;                  
                 foreach($todos as $todo) {
                   if(is_int($rc/2)) { 
                     echo '<tr class="even"';                               
                   } else { 
                       echo '<tr class="odd"'; 
                   }
                   $rc++;
                   echo ' id="row'.$todo->id.'" onclick="rowselect(\''.$todo->id.'\')"><td><input type="checkbox" id="check'.$todo->id.'" name="todo'.$todo->id.'" value="'.$todo->id.'" onclick="rowselect(\''.$todo->id.'\')" /></td><td';
                   if(strlen($todo->description) > 40) {
                     echo ' onmouseover="overlay(this, \'todo'.$itemno.'\')" onmouseout="overlayclose(\'todo'.$itemno.'\')"><a href="'.$_SESSION['IZ_CALURL'].'index.php?todo=1&amp;act=viewtodo&amp;id='.$todo->id.'&amp;from=events&#46;act&#45;manage&#46;view&#45;list">'.$todo->title.'</a>
                          </td><td>',nobreaks(substr(strip_tags($todo->description),0,40)),'...';
                     $itemno++;
                   } else {
                     echo '><a href="'.$_SESSION['IZ_CALURL'].'index.php?todo=1&amp;act=viewtodo&amp;id='.$todo->id.'&amp;from=events&#46;act&#45;manage&#46;view&#45;list">'.$todo->title.'</a>';                   
                     echo '</td><td>';
                     echo nobreaks(strip_tags($todo->description),'<img><p><span>');
                   }
                   echo '</td><td>';
                   if($todo->due == 0) {
                     echo STR_ONGOING;
                   } else {
                     echo date("Y-m-d",$todo->due);
                   }
                   echo '</td><td>',$_SESSION['todocats'][$todo->category]->name,'</td>';
                   if($_SESSION['cust1'] != 'none') { echo '<td>',$todo->cust1,'</td>'; }
                   if($_SESSION['cust2'] != 'none') { echo '<td>',$todo->cust2,'</td>'; }
                   if($_SESSION['cust3'] != 'none') { echo '<td>',$todo->cust3,'</td>'; }
                   echo '</tr>';
                 }  
                 echo '</tbody></table><input type="hidden" name="from" value="events-1.act-manage.view-list" />';
                 echo '<input type="hidden" name="events" value="events" /></form>';
           }
         }
       } else {
         echo '<span>&#35;211&#58; ',ERR_NOPERMISSION,'</span>';
       }
}
/**
* Shows a form with all/none/invert buttons for editing the items selected in the events/tasks table.
*/
function getmassactions() {
       global $onload;
       echo '<form enctype="multipart/form-data" method="post" name="massedit" action="',$_SESSION['IZ_CALURL'],'index.php">
             <div class="massactions"><div>',STR_SELECTION,
               '&#58; <input type="button" value="',STR_ALL,'" name="selectall" id="mousehookselectall" class="nicebutton" />
                <input type="button" value="',STR_NONE,'" name="selectnone" id="mousehookselectnone" class="nicebutton" />
                <input type="button" value="',STR_INVERT,'" name="selectinvert" id="mousehookselectinvert" class="nicebutton" /></div>
             <div>',STR_WSELECTED,'&#58; ';
       if($_SESSION['edit'] > 0) { 
         echo '<button type="submit" value="edit" name="mass" class="nicebutton">',STR_EDIT,'</button>'; 
       }
       if($_SESSION['delete'] > 0) { 
         echo '<button type="button" id="massdeletebutton" class="nicebutton">',STR_DELETE,'</button>';
         $onload .= 'listen(\'click\',\'massdeletebutton\',massdelete);'."\n";
       }
                   echo '<button type="submit" value="getical" name="act" class="nicebutton">'.STR_EXPICAL.'</button>
                         <input type="hidden" name="type" value="ids" /></div></div>';
       $onload .= 'listen(\'click\',\'mousehookselectall\',setchecks(\'all\'));'."\n".
                  'listen(\'click\',\'mousehookselectnone\',setchecks(\'none\'));'."\n".
                  'listen(\'click\',\'mousehookselectinvert\',setchecks(\'invert\'));'."\n";
}
/**
* Adds an event based on $_POST variables.
*/
function addevent() {
         global $numqs;
         global $error;
         if($_SESSION['edit'] > 0) {
           if(!empty($_POST['addevtitle'])) { $evtitle = $_POST['addevtitle']; } else { $localerror = 1; $error .= '<p>'.ERR_ERRORTEXT."&#58; </strong>".ERR_EVENTNONAME.'</p>'; }
           $evtask = $_POST['addevtask'];
           $startdate = $_POST['addevstartdate'];
           list($startday,$startmonth,$startyear) = explode("/",$startdate);
           if(($_SESSION['IZ_OPT'] & OPT_ENDDATE) != 0) {
             if(intval($_POST['addevallday'] == 1)) {
               $alldayevent = 1;
               $starthour = 0;
               $startminute = 0;
             } else {
               $alldayevent = 0;
               $starthour = intval($_POST['addevstarthour']);
               $startminute = intval($_POST['addevstartminute']);
             }
             $evstart = mktime($starthour,$startminute,0,intval($startmonth),intval($startday),intval($startyear));
             $enddate = $_POST['addevenddate'];
             list($endday,$endmonth,$endyear) = explode("/",$enddate);
             $endhour = intval($_POST['addevendhour']);
             $endminute = intval($_POST['addevendminute']);
             $evend = mktime($endhour,$endminute,0,intval($endmonth),intval($endday),intval($endyear));
           } else {
             $alldayevent = 1;
             $starthour = 0;
             $startminute = 0;
             $evstart = mktime(0,0,0,intval($startmonth),intval($startday),intval($startyear));
             $evend = $evstart+86399;
           }
           $cust1 = $_POST['addevcust1'];
           $cust2 = $_POST['addevcust2'];
           $cust3 = $_POST['addevcust3'];
           $venue = $_POST['addevvenue'];
           $linkgoogle = intval($_POST['addevlinkgoogle']);
           $status = $_POST['addevstatus'];
           $icon = intval($_POST['addeventicon']);
           $cn = substr(trim($_POST['addevcategory']),0,3);
           if($cn == 'nce') {
             $category = gen_id();
             $newcatname = substr($_POST['addevcategory'],3,strlen($_POST['addevcategory']));
             add_category($category,$newcatname,'event','#000000');
             rebuild_cats('events');
           } else {
             $category = $_POST['addevcategory'];
           };
           $attendees = input2attendees($_POST['addevattendees']);
           if(!isset($_POST['addevallowcomments'])) {
             $comments = 0;
           } else {
             $comments = 1;
           }
           $evid = gen_id();
           if($_POST['recurs'] == 'none') {
             $maininstanceof = '';
           } else {
             $maininstanceof = $evid;         
           }
           $author = trim($_SESSION['uname']);
           $mainevent = new event(new eventres($evid,$category,$evstart,$evend,$evtitle,$evtask,$venue,$linkgoogle,$alldayevent,$maininstanceof,$status,$author,$cust1,$cust2,$cust3,$attendees,$comments,$icon));
           if($_POST['recurs'] == 'none') {
             if($mainevent->insert() == false) {
               echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_ADDING,'</span><br />';
               return;
             }
           }
           if(!empty($event->attendees)) {
             $mainevent->sendinvites;
           }
           if($_POST['recurs'] != 'none') {
             switch($_POST['rectype']) {
               case '1':
                 $endtype = 'num';
                 $endval = $_POST['numrecurrences'];
                 break;
               case '2':
                 $endtype = 'num';
                 $endval = intval($_SESSION['IZ_DEFNUMRECS']);
                 break;
               case '3':
                 if(empty($_POST['rendby'])) {
                   $localerror = 1;
                   $error .= '<p>'.ERR_ERRORTEXT."</strong>&#35;49&#58; ".ERR_NOENDDATE.'</p>';
                 } else {
                   list($rendbyday,$rendbymonth,$rendbyyear) = explode("/",$_POST['rendby']);
                   $endtype = 'date';
                   $endval = mktime(0,0,0,$rendbymonth,$rendbyday,$rendbyyear);
                 }
                 break;
               }
//var_dump($_POST);
//echo '<br>'.$endval.'-'.$_POST['rectype'].'--';
             switch($_POST['recurs']) {
               case 'daily':
                 if($_POST['dayperiod'] == 'everyxdays') {
                   $recinterval = $_POST['xdays'];
                   if($mainevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   addrecurring('daily',$endtype,$endval,$mainevent,'xdays',$recinterval);
                 } elseif($_POST['dayperiod'] == 'everyweekday') {
                   if((date('l',$mainevent->eventstart) != 'Saturday') && (date('l',$mainevent->eventstart) != 'Sunday')) {
                     if($mainevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                   } else {
                     if($endtype == 'num') {
                       $endval++;
                     }
                   }
                   addrecurring('daily',$endtype,$endval,$mainevent,'weekdays',false);
                 }
                 break;
               case "weekly":
                 $recinterval = $_POST['xweeks'];
                 $recurdays = array(
                   'Monday' => '0',
                   'Tuesday' => '0',
                   'Wednesday' => '0',
                   'Thursday' => '0',
                   'Friday' => '0',
                   'Saturday' => '0',
                   'Sunday' => '0',
                 );
                 if($_POST['recurmonday']) { $recurdays['Monday'] = '1'; }
                 if($_POST['recurtuesday']) { $recurdays['Tuesday'] = '1'; }
                 if($_POST['recurwednesday']) { $recurdays['Wednesday'] = '1'; }
                 if($_POST['recurthursday']) { $recurdays['Thursday'] = '1'; }
                 if($_POST['recurfriday']) { $recurdays['Friday'] = '1'; }
                 if($_POST['recursaturday']) { $recurdays['Saturday'] = '1'; }
                 if($_POST['recursunday']) { $recurdays['Sunday'] = '1'; }
                 $mainday = date('l',$mainevent->eventstart);
                 if($recurdays[$mainday]) {
                   if($mainevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                 } else {
                   if($endtype == 'num') {
                     $endval++;
                   }
                 }
                 addrecurring('weekly',$endtype,$endval,$mainevent,$recurdays,$recinterval);
                 break;
           case 'monthly':
                 if($_POST['monthtype'] == 'dayxofy') {
                   if(!empty($_POST['xmonthday'])) { $monthday = $_POST['xmonthday']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT." &#35;762&#58; </strong>".ERR_MONTHNODAY."<br />"; }
                   if(!empty($_POST['xmonthmonths'])) { $xmonths = $_POST['xmonthmonths']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT." &#35;763&#58; </strong>".ERR_MONTHNOMONTH."<br />"; }
                   if(date('j',$mainevent->eventstart) == $monthday) {
                     if($mainevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                   } else {
                     if($endtype == 'num') {
                       $endval++;
                     }
                   }
                   addrecurring('monthly',$endtype,$endval,$mainevent,'xofy',$monthday, $xmonths);
                 } elseif($_POST['monthtype'] == 'dayxofyeveryz') {
                   if(empty($_POST['monthinterval'])) { $localerror = 1; $error .= "<p><strong>".ERR_ERRORTEXT." &#35;764&#58; </strong>".ERR_MONTHNOMONTH."</p>"; } else { $monthint = $_POST['monthinterval']; }
                   if(strlen($_POST['monthinttype']) == 0) { $localerror = 1; $error .= "<p><strong>".ERR_ERRORTEXT." &#35;765&#58; </strong>".ERR_MONTHNOMONTH."</p>"; } else { $monthinttype = $_POST['monthinttype']; }
                   if(empty($_POST['xmonthmonths2'])) { $localerror = 1; $error .= "<p><strong>".ERR_ERRORTEXT." &#35;766&#58; </strong>".ERR_MONTHNOMONTH."</p>"; } else { $xmonths = $_POST['xmonthmonths2']; }
                   if(getdayvalues($mainevent->eventstart, $monthint, $monthinttype) == true) {
                     if($mainevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                   } else {
                     if($endtype == 'num') {
                       $endval++;
                     }
                   }
                   addrecurring('monthly',$endtype,$endval,$mainevent,'xofyeveryz',$monthint, $xmonths, $monthinttype);
                 }
                 break;
               case 'yearly':
                 if($_POST['yeartype'] == 'yeartype1') {
                   if(!empty($_POST['yearrecmonth'])) { $recmonth = $_POST['yearrecmonth']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT."</strong>".ERR_YEARNOMONTH."<br />"; }
                   if(!empty($_POST['yearlydate'])) { $recdate = $_POST['yearlydate']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT."</strong>".ERR_YEARNODAY."<br />"; }
                   if((date('n',$mainevent->eventstart) == $recmonth) && (date('j',$mainevent->eventstart) == $recdate)) {
                     if($mainevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                   } else {
                     if($endtype == 'num') {
                       $endval++;
                     }
                   }
                   addrecurring('yearly',$endtype,$endval,$mainevent,'type1',$recmonth,$recdate);
                 } elseif($_POST['yeartype'] == 'yeartype2') {
                   if(!empty($_POST['yearrecint'])) { $recmonthint = $_POST['yearrecint']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT."</strong>".ERR_MONTHNOMONTH."<br />"; }
                   if(!empty($_POST['yearrectype'])) { $recmonthtype = $_POST['yearrectype']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT."</strong>".ERR_MONTHNOMONTH."<br />"; }
                   if(!empty($_POST['yearrecmonth2'])) { $recmonth2 = $_POST['yearrecmonth2']; } else { $localerror = 1; $error .= "<strong>".ERR_ERRORTEXT."</strong>".ERR_YEARNOMONTH."<br />"; }
                   if((date('n',$instancestart) == $recmonth2) && (getdayvalues($mainevent->eventstart, $recmonthint, $recmonthtype) == true)) {
                     if($mainevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;48&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                   } else {
                     if($endtype == 'num') {
                       $endval++;
                     }
                   }
                   addrecurring('yearly',$endtype,$endval,$mainevent,'type2',$recmonthint,$recmonthtype, $recmonth2);
                 }
                 break;
             }
           }
         } else {
                  echo '<span>&#35;212&#58; ',ERR_NOPERMISSION,'</span>';
         }
}
/**
* Manages the recursion of an event and adds multiple instances.
*/
function addrecurring($type, $endtype, $endval, $eventobj, $par1, $par2, $par3 = '', $par4 = '') {
     $category = $eventobj->category;
     $starthour = date('G',$eventobj->eventstart);
     $startminute = date('i',$eventobj->eventstart);
     $startmonth = date('n',$eventobj->eventstart);
     $startday = date('j',$eventobj->eventstart);
     $startyear = date('Y',$eventobj->eventstart);
     $endhour = date('G',$eventobj->eventend);
     $endminute = date('i',$eventobj->eventend);
     $endmonth = date('n',$eventobj->eventend);
     $endday = date('j',$eventobj->eventend);
     $endyear = date('Y',$eventobj->eventend);
     $evtitle = $eventobj->title;
     $evtask = $eventobj->description;
     $venue = $eventobj->venue;
     $linkgoogle = $eventobj->linkgoogle;
     $alldayevent = $eventobj->allday;
     $status = $eventobj->status;
     $cust1 = $eventobj->cust1;
     $cust2 = $eventobj->cust2;
     $cust3 = $eventobj->cust3;
     $attendees = $eventobj->attendees;
     $comments = $eventobj->comments;
     $instance = $eventobj->id;
     $icon = $eventobj->icon;
/*
echo 'type: '.$type.'<br />';
echo 'endtype: '.$endtype.'<br />';
echo 'endval: '.$endval.'<br />';
echo 'eventobj: '; var_dump($eventobj); echo '<br />';
echo 'eventobj->eventstart: '.date('r',$eventobj->eventstart).'<br />';
echo 'eventobj->eventend: '.date('r',$eventobj->eventend).'<br />';
echo 'par1: '.$par1.'<br />';
echo 'par2: '.$par2.'<br />';
echo 'par3: '.$par3.'<br />';
echo 'par4: '.$par4.'<br />';
//die(); */
         if($type == 'daily') {
           if($par1 == 'xdays') {
             if(!$localerror) {
               if($endtype == 'num') {
                 $cyclenum = 1;
                 while($cyclenum<$endval) {
                   $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+($par2*$cyclenum),$startyear);
                   $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+($par2*$cyclenum),$endyear);
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;50&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                   $cyclenum++;
                 }
               } else {
                 $cyclenum = 1;
                 $instancestart = $evstart;
                 while($instancestart<$endval) {
                   $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+($par2*$cyclenum),$startyear);
                   $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+($par2*$cyclenum),$endyear);
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;51&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                   $cyclenum++;
                 }
               }
              } /* END ERROR HANDLER */
           } elseif($par1 == 'weekdays') {
             if($endtype == 'num') {
               $timesentered = 1;
               $cyclenum = 1;
               while($timesentered<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if((date('l',$instancestart) != 'Saturday') && (date('l',$instancestart) != 'Sunday')) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;52&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                   $timesentered++;
                 }
                 $cyclenum++;
               }
             } else {
               $cyclenum = 1;
               $instancestart = $evstart;
               while($instancestart<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if((date('l',$instancestart) != 'Saturday') && (date('l',$instancestart) != 'Sunday')) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;53&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                 }
                 $cyclenum++;
               }
             }
           }   /* END EVERY WEEKDAY */
         } elseif($type == 'weekly') {
           if($endtype == 'num') {
             $timesentered = 1;
             $cyclenum = 1;
             $weeknum = 0;            
             while($timesentered<$endval) {               
               $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
               $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
               if(($weeknum % $par2) == 0) {
                 $dayname = date('l',$instancestart);
                 if($par1[$dayname]) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;54&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                   $timesentered++;
                 }
               }
               if(date('w',$instancestart) == 0) { $weeknum++; }
               $cyclenum++;
             }
           } else { /* END WEEKLY RECUR 'X' TIMES */
             $cyclenum = 1;
             $instancestart = $evstart;
             while($instancestart<$endval) {
               $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
               $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
               if(($weeknum % $par2) == 0) {
                 $dayname = date('l',$instancestart);
                 if($par1[$dayname]) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;55&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                 }
               }
               if(date('w',$instancestart) == 0) { $weeknum++; }
               $cyclenum++;
             }
           }
         } elseif($type == 'monthly') {
           if($par1 == 'xofy') {
//            function: addrecurring($type, $endtype, $endval, $eventobj, $par1, $par2, $par3 = '', $par4 = '')
//                             addrecurring('monthly',$endtype,$endval,$mainevent,'xofy',$monthday, $xmonths);
             if($endtype == 'num'){
               $timesentered = 1;
               $cyclenum = 1;
               $monthnum = 0;
               while($timesentered<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(($monthnum % $par3) == 0) {
                   if(date('j',$instancestart) == $par2) {
                     $newevent = clone($eventobj);
                     $newevent->newinstance($instancestart,$instanceend);
                     if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;56&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 if(islastday($instancestart)) { $monthnum++; }
                 $cyclenum++;
               }
             } else {
               $cyclenum = 1;
               $instancestart = $evstart;
               while($instancestart<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(($monthnum % $par3) == 0) {
                   if(date('j',$instancestart) == $par2) {
                     $newevent = clone($eventobj);
                     $newevent->newinstance($instancestart,$instanceend);
                     if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;57&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 if(islastday($instancestart)) { $monthnum++; }
                 $cyclenum++;
               }
             }
           } elseif($par1 == 'xofyeveryz') {
//                   addrecurring('monthly',$endtype,$endval,$mainevent,'xofyeveryz',$monthint, $xmonths, $monthinttype);
             if($endtype == 'num') {
               $timesentered = 1;
               $cyclenum = 1;
               $monthnum = 0;
               while($timesentered<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(($monthnum % $par3) == 0) {
                   if(getdayvalues($instancestart, $par2, $par4) == true) {
                     $newevent = clone($eventobj);
                     $newevent->newinstance($instancestart,$instanceend);
//echo date('jS F Y',$newevent->eventstart);
                     if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;58&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 if(islastday($instancestart)) { $monthnum++; }
                 $cyclenum++;
               }
             } else {
             $cyclenum = 1;
             $instancestart = $evstart;
             while($instancestart<$endval) {
               $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
               $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(($monthnum % $par3) == 0) {
                   if(getdayvalues($instancestart, $par2, $par4) == true) {
                     $newevent = clone($eventobj);
                     $newevent->newinstance($instancestart,$instanceend);
                     if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;59&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 if(islastday($instancestart)) { $monthnum++; }
                 $cyclenum++;
               }
             }
           }  
         } elseif($type == 'yearly') {
           if($par1 == 'type1') {
//                   addrecurring('yearly',$endtype,$endval,$mainevent,'type1',$recmonth,$recdate);
             if($endtype == 'num') {
               $timesentered = 1;
               $cyclenum = 1;
               while($timesentered<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if((date('n',$instancestart) == $par2) && (date('j',$instancestart) == $par3)) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;60&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $timesentered++;
                   $numqs++;
                 }
                 $cyclenum++;
               }
             } else {
               $cyclenum = 1;
               $instancestart = $evstart;
               while($instancestart<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if((date('n',$instancestart) == $par2) && (date('j',$instancestart) == $par3)) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                     echo '<span style="color: #ff0000; font-weight: bold;">&#35;61&#58; ',ERR_FILEOPEN,'</span><br />';
                     return;
                   }
                   $numqs++;
                 }
                 $cyclenum++;
               }
             }
           } elseif($par1 == 'type2') {
//                   addrecurring('yearly',$endtype,$endval,$mainevent,'type2',$recmonthint,$recmonthtype, $recmonth2);
             if($endtype == 'num'){
               $timesentered = 1;
               $cyclenum = 1;
               while($timesentered<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(date('n',$instancestart) == $par4) {
                   if(getdayvalues($instancestart, $par2, $par3) == true) {
                   $newevent = clone($eventobj);
                   $newevent->newinstance($instancestart,$instanceend);
                   if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;62&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 $cyclenum++;
               }
             } else {
               $cyclenum = 1;
               $instancestart = $evstart;
               while($instancestart<$endval) {
                 $instancestart = mktime($starthour,$startminute,0,$startmonth,$startday+$cyclenum,$startyear);
                 $instanceend = mktime($endhour,$endminute,0,$endmonth,$endday+$cyclenum,$endyear);
                 if(date('n',$instancestart) == $par4) {
                   if(getdayvalues($instancestart, $par2, $par3) == true) {
                     $newevent = clone($eventobj);
                     $newevent->newinstance($instancestart,$instanceend);
                     if($newevent->insert() == false) {
                       echo '<span style="color: #ff0000; font-weight: bold;">&#35;63&#58; ',ERR_FILEOPEN,'</span><br />';
                       return;
                     }
                     $numqs++;
                     $timesentered++;
                   }
                 }
                 $cyclenum++;
               }
             }
           }
         } /* END YEARLY RECURRENCE */
}
/**
* Edits an event based on $_POST variables.
*/
function edit_event() {
         global $numqs;
         global $error;
         if(empty($_POST['editevtitle'])) {
           $error .= '<p>'.ERR_EVENTNONAME.'</p>';
         } else {
           if(intval($_POST['editevallday'] == 1)) {
               $alldayevent = 1;
               $starthour = 0;
               $startminute = 0;
           } else {
               $alldayevent = 0;
               $starthour = $_POST['editevstarthour'];
               $startminute = $_POST['editevstartminute'];
           }
           if($_POST['editevlinkgoogle']) {
             $linkgoogle = 1;
           } else {
             $linkgoogle = 0;
           }
           $cn = substr(trim($_POST['editevcategory']),0,3);
           if($cn == 'nce') {
             $category = gen_id();
             $newcatname = substr($_POST['editevcategory'],3,strlen($_POST['editevcategory']));
             add_category($category,$newcatname,'event','#000000');
             rebuild_cats('events');
           } else {
             $category = $_POST['editevcategory'];
           }
           $startdate = $_POST['editevstartdate'];
           list($startday,$startmonth,$startyear) = explode("/",$startdate);         
           $evstart = mktime($starthour,$startminute,0,$startmonth,$startday,$startyear);
           $enddate = $_POST['editevenddate'];
           list($endday,$endmonth,$endyear) = explode("/",$enddate);
           $endhour = intval($_POST['editevendhour']);
           $endminute = intval($_POST['editevendminute']);
           $evend = mktime($endhour,$endminute,0,intval($endmonth),intval($endday),intval($endyear));
           $comments = intval($_POST['editevallowcomments']);
           $event = new event(new eventres($_POST['id'],$category,$evstart,$evend,$_POST['editevtitle'],$_POST['editevtask'],$_POST['editevvenue'],$linkgoogle,$alldayevent,$_POST['instanceof'],$_POST['editevstatus'],$_POST['author'],$_POST['editevcust1'],$_POST['editevcust2'],$_POST['editevcust3'],$_POST['editevattendees'],$comments,$_POST['editeventicon']));
           if((($_SESSION['edit'] == 1 
               && ((strtolower($event->author) == strtolower($_SESSION['uname']))
                 || ($event->status == 'Public'
                 || (strtolower($event->author) == 'everyone'))))
                 || ($_SESSION['edit'] == 2))
             ) {
             $event->edit();
           } else {
             iz_error(ERR_NOPERMISSION);
           }
     }
}
/**
* Echoes how many events there are in a series.
* @param parentid The ID of the parent event
* @param type Controls the output format (Event/Table)
*/
function getserieslength($parentid, $type) {
   if(IZ_CALMODE == 'mysql') {
     if($_SESSION['MYSQLi']) {
       global $dblink;
       $res = $dblink->query(sprintf("SELECT id FROM events WHERE instanceof = '%s'",$dblink->real_escape_string($parentid)));
       $num->num_rows;
       $res->close();
     } else {
       $qry = mysql_query(sprintf("SELECT id FROM events WHERE instanceof = '%s'",mysql_real_escape_string($parentid)));
       $num = mysql_num_rows($qry);
     }
   } elseif(IZ_CALMODE == 'postgre') {
     $qry = pg_query(sprintf("SELECT \"id\" FROM \"events\" WHERE \"instanceof\" = '%s'",pg_escape_string($parentid)));
     $num = pg_num_rows($qry);
   } elseif(IZ_CALMODE == 'msq') {
     $qry = mssql_query(sprintf("SELECT id FROM events WHERE instanceof = '%s'",mssql_escape_string($parentid)));
     $num = mssql_num_rows($qry);
   }
   if($type == 'p') {
     echo '<p class="eventmeta" style="margin: 0 0 5px 205px;">',str_replace('{0}','<strong>'.$num.'</strong>',STR_EVSERIES), '</p>';
   } elseif($type == 'table') {
     echo '<tr><td>&nbsp;</td><td><p class="eventmeta">',str_replace('{0}','<strong>'.$num.'</strong>',STR_EVSERIES), '</p></td></tr>';
   }
}
/**
* Saves a series of events with values from $_POST.
*/
function saveseries() {
   list($startday,$startmonth,$startyear) = explode("/",$_POST['editevstartdate']);
   $starthour = intval($_POST['editevstarthour']);
   $startminute = intval($_POST['editevstartminute']); 
   $start = mktime($starthour,$startminute,0,$startmonth,$startday,$startyear);
   list($endday,$endmonth,$endyear) = explode("/",$_POST['editevenddate']); 
   $endhour = intval($_POST['editevendhour']);
   $endminute = intval($_POST['editevendminute']);                          
   $end = mktime($endhour,$endminute,0,$endmonth,$endday,$endyear);
   if($_POST['editevlinkgoogle']) {
     $linkgoogle = 1;
   } else {
     $linkgoogle = 0;
   }
   $event = new event(new eventres($_POST['instanceof'],$_POST['editevcategory'],$start,$end,$_POST['editevtitle'],$_POST['editevtask'],$_POST['editevvenue'],$linkgoogle,intval($_POST['editevallday']),$_POST['evinstanceof'],$_POST['editevstatus'],$_POST['author'],$_POST['editevcust1'],$_POST['editevcust2'],$_POST['editevcust3'],$_POST['editevattendees'],$_POST['editevcomments'],$_POST['editeventicon']));
   if(($_SESSION['edit'] == 1 && (strtolower($event->author) == strtolower($_SESSION['uname']) || (strtolower($event->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) {
     $event->saveseries();
   } else {
     iz_error(ERR_NOPERMISSION);
   }
}
/**
* Saves events and tasks edited from the mass edit page.
*/
function masssave() {
         global $numqs;
         $massids = explode("-",$_POST['ids']);
         $actiontodos = array();
           foreach($massids as $id) {
           $idstring = substr($id,1,8);
             if(substr($id,0,1) == 'e') {
               list($startday,$startmonth,$startyear) = explode("/",$_POST[$idstring.'startdate']);     
               $starthour = intval($_POST[$idstring.'starthour']);
               $startminute = intval($_POST[$idstring.'startminute']);
               $start = mktime($starthour,$startminute,0,intval($startmonth),intval($startday),intval($startyear));
               list($endday,$endmonth,$endyear) = explode("/",$_POST[$idstring.'enddate']); 
               $endhour = intval($_POST[$idstring.'endhour']);
               $endminute = intval($_POST[$idstring.'endminute']);                          
               $end = mktime($endhour,$endminute,0,intval($endmonth),intval($endday),intval($endyear));
               if(intval($_POST[$idstring.'linkgoogle']) == 1) {
                 $linkgoogle = 1;
               } else {
                 $linkgoogle = 0;
               }
               $cn = substr(trim($_POST[$idstring.'evcategory']),0,3);
               if($cn == 'nce') {
                 $category = gen_id();
                 $newcatname = substr($_POST[$idstring.'evcategory'],3,strlen($_POST[$idstring.'evcategory']));
                 add_category($category,$newcatname,'event','#000000');
                 rebuild_cats('events');
               } else {
                 $category = $_POST[$idstring.'evcategory'];
               }
//var_dump($_POST);
//print($idstring.'-'.$_POST[$idstring.'evcategory'].'-'.$start.'-'.$end.'-'.$_POST[$idstring.'evtitle'].'-'.$_POST[$idstring.'evtask'].'-'.$_POST[$idstring.'venue']);
//echo $idstring.'-'.$_POST[$idstring.'icon'];
               $event = new event(new eventres($idstring,$category,$start,$end,$_POST[$idstring.'evtitle'],$_POST[$idstring.'evtask'],$_POST[$idstring.'venue'],$linkgoogle,intval($_POST[$idstring.'allday']),$_POST[$idstring.'evinstanceof'],$_POST[$idstring.'status'],'0',$_POST[$idstring.'cust1'],$_POST[$idstring.'cust2'],$_POST[$idstring.'cust3'],$_POST[$idstring.'attendees'],$_POST[$idstring.'allowcomments'],$_POST[$idstring.'icon']));
               if(($_SESSION['edit'] == 1 
                    && (strtolower($event->author) == strtolower($_SESSION['uname']) 
                    || (strtolower($event->author) == 'everyone')
                  )) 
                  || ($_SESSION['edit'] == 2)) {
                 $event->edit();
               } else {
                 echo '<span>&#35;152&#58; ',ERR_NOPERMISSION,'</span><br />';
               }
             } elseif(substr($id,0,1) == 't') {
               if(empty($_POST[$idstring.'datedue'])) {
                 $due = 0;
               } else {
                 list($dueday,$duemonth,$dueyear) = explode("/",$_POST[$idstring.'datedue']);     
                 $due = mktime(0,0,0,intval($duemonth),intval($dueday),intval($dueyear));
               }
               $cn = substr(trim($_POST[$idstring.'taskcategory']),0,3);
               if($cn == 'nce') {
                 $category = gen_id();
                 $newcatname = substr($_POST[$idstring.'taskcategory'],3,strlen($_POST[$idstring.'taskcategory']));
                 add_category($category,$newcatname,'event','#000000');
                 rebuild_cats('events');
               } else {
                 $category = $_POST[$idstring.'taskcategory'];
               }
               $todo = new todo(new todores($idstring,$category,'0',$due,$_POST[$idstring.'taskname'],$_POST[$idstring.'task'],'0','0',$_POST[$idstring.'cust1'],$_POST[$idstring.'cust2'],$_POST[$idstring.'cust3'],$_POST[$idstring.'allowcomments'],$_POST[$idstring.'status'],$_POST[$idstring.'icon']));
               if(($_SESSION['edit'] == 1 && (strtolower($todo->author) == strtolower($_SESSION['uname']) || (strtolower($todo->author) == 'everyone'))) || ($_SESSION['edit'] == 2)) {
                 $todo->edit();
               } else {
                 echo '<span>&#35;152&#58; ',ERR_NOPERMISSION,'</span><br />';
               }
             }
           }
}
/**
* Displays a form for editing multiple events/tasks.
*/
function massedit() {
    global $numqs;
    global $onload;
    global $cals;
    $opt_flags = $_SESSION['IZ_OPT'];
//var_dump($_POST);
    if(($_SESSION['edit'] > 0) || ($_SESSION['delete'] > 0)) {
        echo '<form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" id="massedit" name="massedit" onsubmit="return validate_mass();">
        <div class="massactions"><button type="submit" value="save" name="masssave" class="buttonsmall">'.STR_SAVE.'</button></div>';
        $events = array();
        $todos = array();
        izsql();
        if(IZ_CALMODE == 'mysql' ) {
          if($_SESSION['MYSQLi']) {
            global $dblink;
            foreach($_POST as $var => $id) {
                if(($var != 'mass') && ($var != 'events') && ($var != 'from')) {
                    if(substr($var,0,4) == 'even') {
                        $massids[] = 'e'.substr($var,4,8);
                        $eventsql = sprintf("SELECT * FROM events WHERE id='%s'",$dblink->real_escape_string(substr($var,4,8)));
                        $eventres = $dblink->query($eventsql);
                        $numqs++;
                        $sqlevent = $eventres->fetch_object();
                        $events[] = new event($sqlevent);
                        $eventres->close();
                    } elseif(substr($var,0,4) == 'todo') {
                        $massids[] = 't'.substr($var,4,8);
                        $todosql = sprintf("SELECT * FROM tasks WHERE id='%s'",$dblink->real_escape_string(substr($var,4,8)));
                        $todores = $dblink->query($todosql);
                        $numqs++;
                        $sqltodo = $todores->fetch_object();
                        $todos[] = new todo($sqltodo);
                        $todores->close();
                    }
                }
            }
          } else {
            foreach($_POST as $var => $id) {
                if(($var != 'mass') && ($var != 'events') && ($var != 'from')) {
                    if(substr($var,0,4) == 'even') {
                        $massids[] = 'e'.substr($var,4,8);
                        $eventsql = sprintf("SELECT * FROM events WHERE id='%s'",mysql_real_escape_string(substr($var,4,8)));
                        $eventqry = mysql_query($eventsql);
                        $numqs++;
                        $sqlevent = mysql_fetch_object($eventqry);
                        $events[] = new event($sqlevent);
                    } elseif(substr($var,0,4) == 'todo') {
                        $massids[] = 't'.substr($var,4,8);
                        $todosql = sprintf("SELECT * FROM tasks WHERE id='%s'",mysql_real_escape_string(substr($var,4,8)));
                        $todoqry = mysql_query($todosql);
                        $numqs++;
                        $sqltodo = mysql_fetch_object($todoqry);
                        $todos[] = new todo($sqltodo);
                    }
                }
            }
          }
        } elseif(IZ_CALMODE == 'postgre') {
            foreach($_POST as $var => $id) {
                if(($var != 'mass') && ($var != 'events') && ($var != 'from')) {
                    if(substr($var,0,4) == 'even') {
                        $massids[] = 'e'.substr($var,4,8);
                        $eventsql = sprintf("SELECT * FROM \"events\" WHERE \"id\"='%s'",pg_escape_string(substr($var,4,8)));
                        $eventqry = pg_query($eventsql);
                        $numqs++;
                        $sqlevent = pg_fetch_object($eventqry);
                        $events[] = new event($sqlevent);
                    } elseif(substr($var,0,4) == 'todo') {
                        $massids[] = 't'.substr($var,4,8);
                        $todosql = sprintf("SELECT * FROM \"tasks\" WHERE \"id\"='%s'",pg_escape_string(substr($var,4,8)));
                        $todoqry = pg_query($todosql);
                        $numqs++;
                        $sqltodo = pg_fetch_object($todoqry);
                        $todos[] = new todo($sqltodo);
                    }
                }
            }
        } elseif(IZ_CALMODE == 'msq') {
            foreach($_POST as $var => $id) {
                if(($var != 'mass') && ($var != 'events') && ($var != 'from')) {
                    if(substr($var,0,4) == 'even') {
                        $massids[] = 'e'.substr($var,4,8);
                        $eventsql = sprintf("SELECT * FROM events WHERE id='%s'",mssql_escape_string(substr($var,4,8)));
                        $eventqry = mssql_query($eventsql);
                        $numqs++;
                        $sqlevent = mssql_fetch_object($eventqry);
                        $events[] = new event($sqlevent);
                    } elseif(substr($var,0,4) == 'todo') {
                        $massids[] = 't'.substr($var,4,8);
                        $todosql = sprintf("SELECT * FROM tasks WHERE id='%s'",mssql_escape_string(substr($var,4,8)));
                        $todoqry = mssql_query($todosql);
                        $numqs++;
                        $sqltodo = mssql_fetch_object($todoqry);
                        $todos[] = new todo($sqltodo);
                    }
                }
            }
        }
        if(!empty($todos)) {
          foreach($todos as $todo) {
            if($_SESSION['cpanel'] == 1
               || ($_SESSION['edit'] == 1 
                    && (strtolower($todo->author) == strtolower($_SESSION['uname']) 
                    || strtolower($todo->author) == 'everyone')
                  ) 
               || ($_SESSION['edit'] == 2)) {
              $havepermission = true;  
            } else {
              $havepermission = false;            
            }
            echo '<div class="containerbox massedit" id="',$todo->id,'container">
              <label for="',$todo->id,'taskname">',STR_TASKNAME,'&#58;</label>
              <input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$todo->id,'taskname" tabindex="20" id="',$todo->id,'taskname" class="standard" size="30" value="',dirty($todo->title),'" />
              <div class="inlineerror" id="',$todo->id,'error_taskname">&nbsp;</div><br />
      
              <label for="',$todo->id,'datedue">',STR_DATEDUE,'&#58;</label>
              <div class="datebox"><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$todo->id,'datedue" tabindex="21" size="10" id="',$todo->id,'datedue" class="standard" ';
            if($todo->due != 0) {
              echo 'value="',date("j/m/Y",$todo->due),'" ';
            }
            echo '/><img src="',$_SESSION['IZ_CALURL'],'images/calendar.png" class="datepicker" alt="',STR_DATEDUE,'" id="mousehookdatedue',$todo->id,'" /></div>
              <div class="inlineerror" id="',$todo->id,'error_datedue">&nbsp;</div>
              <br />
      
              <label for="',$todo->id,'task">',STR_TASK,'&#58;</label>
              <textarea ',(!$havepermission ? 'disabled="disabled" ' : ''),'rows="10" name="',$todo->id,'task" tabindex="22" id="',$todo->id,'task" class="standard mceEditor" cols="40">',dirty($todo->description),'</textarea><br />

              <label for="',$todo->id,'taskcategory">',STR_CATEGORY,'&#58;</label>
              <select ',(!$havepermission ? 'disabled="disabled" ' : ''),'name="',$todo->id,'taskcategory" id="',$todo->id,'taskcategory" size="1">';
            get_categories('edit',$todo->category,'task');
            echo '<option id="',$todo->id,'newcattodo" value="newcat">',STR_NEWCATEGORY,'</option>
              </select>
          <br />';
              echo '<input type="hidden" name="',$todo->id,'icon" value="',$todo->icon,'" />';
              if($_SESSION['cust1'] != 'none') {
                echo '<label for="',$todo->id,'cust1">',$_SESSION['cust1'],'&#58;</label>
                <input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$todo->id,'cust1" tabindex="26" id="',$todo->id,'cust1" size="50" class="standard" value="',dirty($todo->cust1),'" /><br />';
      
              } if($_SESSION['cust2'] != 'none') {
                echo '<label for="',$todo->id,'cust2">',$_SESSION['cust2'],'&#58;</label>
                <input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$todo->id,'cust2" tabindex="28" id="',$todo->id,'cust2" size="50" class="standard" value="',dirty($todo->cust2),'" /><br />';
      
              } if($_SESSION['cust3'] != 'none') {
                echo '<label for="',$todo->id,'cust3">',$_SESSION['cust3'],'&#58;</label>
                <input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$todo->id,'cust3" tabindex="30" id="',$todo->id,'cust3" size="50" class="standard" value="',dirty($todo->cust3),'" /><br />';
              }
              echo '</div>';
              $cals .= 'Calendar.setup({inputField:"'.$todo->id.'datedue",button:"mousehookdatedue'.$todo->id.'",displayArea:"mousehookdatedue'.$todo->id.'"});'."\n";
              $onload .= 'listen(\'click\',\''.$todo->id.'taskcategory\',addnewcatfunc(\'todo\',\''.$todo->id.'\'));'."\n";
          }
        }
        if(!empty($events)) {
           foreach($events as $event) {
                if($_SESSION['cpanel'] == 1
                   || ($_SESSION['edit'] == 1 
                        && (strtolower($event->author) == strtolower($_SESSION['uname']) 
                        || strtolower($event->author) == 'everyone')
                      ) 
                   || ($_SESSION['edit'] == 2)) {
                  $havepermission = true;  
                } else {
                  $havepermission = false;
                }
                echo '<div class="containerbox massedit" id="',$event->id,'container">
                <label for="',$event->id,'evtitle">',STR_EVENTNAME,'&#58;</label><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'evtitle" id="',$event->id,'evtitle" class="standard" size="30" value="',dirty($event->title),'" />
                <div class="inlineerror" id="',$event->id,'error_title">&nbsp;</div>
                <br />';
                if(($opt_flags & OPT_ENDDATE) != 0) {
                    echo '<label for="',$event->id,'startbox">',STR_STARTS,'&#58;<br /><small>',STR_ALLDAYINST,'</small></label>
                            <div class="datebox">
                                <div class="dateinput"><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'startdate" size="10" id="',$event->id,'startdate" class="standard" value="',date("j/m/Y",$event->eventstart),'" />
                                  <img src="',$_SESSION['IZ_CALURL'],'images/calendar.png" class="datepicker" alt="',STR_PICKSTART,'" id="mousehookevstart',$event->id,'" />
                                </div>
                                <div class="dateinput"><input type="text" name="',$event->id,'starthour" size="2" id="',$event->id,'starthour" value="',date('H',$event->eventstart),'" class="';
                                    if($event->allday == 1 || !$havepermission) { echo 'boxdisabled" disabled="disabled"'; } else { echo 'small"'; }
                                    echo ' />&#58;<input type="text" name="',$event->id,'startminute" size="2" id="',$event->id,'startminute" value="',date('i',$event->eventstart),'" class="';
                                    if($event->allday == 1 || !$havepermission) { echo 'boxdisabled" disabled="disabled"'; } else { echo 'small"'; }
                                    echo ' />
                                </div>                            
                                <div><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="checkbox" class="inlinecheck" name="',$event->id,'allday" id="',$event->id,'allday" value="1"';
                                    if($event->allday == 1) { echo ' checked="checked"'; } 
                                    echo ' />
                                    <label for="',$event->id,'allday">',STR_ALLDAYDESC,'</label>
                                </div>
                                <div class="inlineerror" id="',$event->id,'error_start">&nbsp;</div>                        
                                <div class="inlineerror" id="',$event->id,'error_allday" style="padding-top: 2px;">&nbsp;</div>                
                            </div>
                            <br />
                            <label for="',$event->id,'enddate">',STR_ENDS,'&#58;</label>
                            <div class="datebox">
                                <div class="dateinput"><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'enddate" size="10" id="',$event->id,'enddate" class="standard" value="',date("j/m/Y",$event->eventend),'" />
                                  <img src="',$_SESSION['IZ_CALURL'],'images/calendar.png" class="datepicker" alt="',STR_PICKEND,'" id="mousehookevend',$event->id,'" />
                                </div>
                                <div class="dateinput"><input type="text" name="',$event->id,'endhour" size="2" id="',$event->id,'endhour" value="',date('H',$event->eventend),'" class="';
                                    if($event->allday == 1 || !$havepermission) { echo 'boxdisabled" disabled="disabled"'; } else { echo 'small"'; }
                                    echo ' />&#58;<input type="text" name="',$event->id,'endminute" size="2" id="',$event->id,'endminute" value="',date('i',$event->eventend),'" class="';
                                    if($event->allday == 1 || !$havepermission) { echo 'boxdisabled" disabled="disabled"'; } else { echo 'small"'; }
                                    echo ' />
                                </div>
                                <div class="inlineerror" id="',$event->id,'error_end">&nbsp;</div>
                            </div>';
                            $cals .= 'Calendar.setup({inputField:"'.$event->id.'startdate",button:"mousehookevstart'.$event->id.'",displayArea:"mousehookevstart'.$event->id.'",onUpdate:function(){document.getElementById(\''.$event->id.'enddate\').value=document.getElementbyId(\''.$event->id.'startdate\').value}});'."\n";
                            if(($opt_flags & OPT_ENDDATE) != 0) {
                              $cals .= 'Calendar.setup({inputField:"'.$event->id.'enddate",button:"mousehookevend'.$event->id.'",displayArea:"mousehookevend'.$event->id.'"});'."\n";
                              $onload .= 'listen(\'click\',\''.$event->id.'allday\',setalldayfunc(\''.$event->id.'\',\'none\'));'."\n";
                            }
                } else {
                  echo '<label for="',$event->id,'startbox">',STR_DATE,'&#58;</label>
                            <div class="datebox">
                                <div class="dateinput">
                                  <input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'startdate" size="10" id="',$event->id,'startdate" class="standard" value="',date("j/m/Y",$event->eventstart),'" />
                                  <img src="',$_SESSION['IZ_CALURL'],'images/calendar.png" class="datepicker" alt="',STR_PICKSTART,'" id="mousehookevstart',$event->id,'" />
                                </div>
                                <div class="inlineerror" id="',$event->id,'error_start">&nbsp;</div>
                            </div>';
                  $cals .= 'Calendar.setup({inputField:"'.$event->id.'startdate",button:"mousehookevstart'.$event->id.'",displayArea:"mousehookevstart'.$event->id.'"});'."\n";
                }
                echo '<br />
                <label for="',$event->id,'evtask">',STR_DESCRIPTION,'&#58;</label><textarea ',(!$havepermission ? 'disabled="disabled" ' : ''),'rows="10" name="',$event->id,'evtask" id="',$event->id,'evtask" class="standard mceEditor" cols="60">',dirty($event->description),'</textarea>
                <br />';
                if(($opt_flags & OPT_ATTENDEES) != 0) {
                    echo '<label for="',$event->id,'attendees">',STR_ATTENDEES,'&#58;</label>',
                         '<textarea ',(!$havepermission ? 'disabled="disabled" ' : ''),'rows="4" name="',$event->id,'attendees" id="',$event->id,'attendees" class="standard" cols="45">',$event->attendees,'</textarea><br />',
                         '<br />';
                }
                if($_SESSION['cust1'] != 'none') {
                    echo '<label for="',$event->id,'cust1">',$_SESSION['cust1'],'&#58;</label><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'cust1" id="',$event->id,'cust1" size="50" class="standard" value="',dirty($event->cust1),'" /><br />';
                }
                if($_SESSION['cust2'] != 'none') {
                    echo '<label for="',$event->id,'cust2">',$_SESSION['cust2'],'&#58;</label><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'cust2" id="',$event->id,'cust2" size="50" class="standard" value="',dirty($event->cust2),'" /><br />';
                }
                if($_SESSION['cust3'] != 'none') {
                    echo '<label for="',$event->id,'cust3">',$_SESSION['cust3'],'&#58;</label><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'cust3" id="',$event->id,'cust3" size="50" class="standard" value="',dirty($event->cust3),'" /><br />';
                }                    
                if(($opt_flags & OPT_VENUE) != 0) {
                    echo '<label for="',$id,'venue">',STR_VENUE,'&#58;</label><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="text" name="',$event->id,'venue" id="',$event->id,'venue" size="30" class="standard" value="',dirty($event->venue),'" /><br />';
                    if(($opt_flags & OPT_GOOGLE) != 0) {
                      echo '<div class="datebox"><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="checkbox" class="optioncheck" name="',$event->id,'linkgoogle" id="',$event->id,'linkgoogle" value="1"';
                      if($event->linkgoogle == 1) {
                        echo ' checked="checked"'; 
                      }
                      echo ' /><label for="',$event->id,'linkgoogle">',STR_LINKGOOGLE,'</label></div><br />';
                    }
                } else {
                  echo '<input type="hidden" name="',$event->id,'venue" id="',$event->id,'venue" value="',dirty($event->venue),'" />';
                }
                if($_SESSION['cpanel'] == 1) {
                  if(strtolower($event->author) == 'everyone') {
                    echo '<label for="',$event->id,'author">',STR_AUTHOR,'&#58;</label> ',STR_NOTLOGGEDIN,'<br />';
                  } else {
                    echo '<label for="',$event->id,'author">',STR_AUTHOR,'&#58;</label> ',$event->author,'<br />';
                  }
                }
                if(($opt_flags & OPT_CATEGORY) != 0) {
                  echo '<label for="',$event->id,'evcategory">',STR_CATEGORY,'&#58;</label>',
                       '<select ',(!$havepermission ? 'disabled="disabled" ' : ''),'name="',$event->id,'evcategory" id="',$event->id,'evcategory" size="1">';
                  get_categories('edit',$event->category);
                  echo '<option id="',$event->id,'newcatevent" value="newcat">',STR_NEWCATEGORY,'</option>',
                       '</select><br />';
                  $onload .= 'listen(\'click\',\''.$event->id.'evcategory\',addnewcatfunc(\'event\',\''.$event->id.'\'));'."\n";
                } else {
                  echo '<input type="hidden" name="',$event->id,'evcategory" id="',$event->id,'evcategory" value="',$_SESSION['defaultcategoryevents'],'" />';
                }
                if($_SESSION['authed'] == 1) {
                  echo '<label>',STR_EVENTSTATUS,'&#58;</label>',
                       '<div class="checks">',
                       '<input type="radio" value="Public" name="',$event->id,'status" class="nomargin" id="',$event->id,'publicstatus"';
                  if($_SESSION['defaultstatus'] == 'Public') {
                    echo ' checked="checked"'; 
                  }
                  echo ' /><label for="',$event->id,'publicstatus" class="plain">',STR_STATUSPUBLIC,'</label>',
                       '<input type="radio" value="Private" name="',$event->id,'status" class="nomargin" id="',$event->id,'privatestatus"';
                  if($_SESSION['defaultstatus'] == 'Private') {
                    echo ' checked="checked"'; 
                  }
                  echo ' /><label for="',$event->id,'privatestatus" class="plain">',STR_STATUSPRIVATE,'</label>',
                       '</div><br />';
                } else {
                  echo '<input type="hidden" name="',$event->id,'status" value="Public" />';
                }
                echo '<input type="hidden" name="',$event->id,'icon" id="',$event->id,'icon" value="',$event->icon,'" />';
                if($_SESSION['IZ_ALLOWCOMMENTS'] == 'author') {
                  echo '<label>',STR_ALLOWCOMMENTS,'&#58;</label>
                          <div><input ',(!$havepermission ? 'disabled="disabled" ' : ''),'type="checkbox" name="',$event->id,'allowcomments" id="',$event->id,'allowcomments" class="inlinecheck" tabindex="19" value="1" />
                            <label for="',$event->id,'allowcomments" class="plain">',STR_ENABLED,'</label></div><br />';
                }
                echo '</div> <!-- ',$event->id,'container" -->
                     
                     ';
           }
        }
        echo '<input type="hidden" name="events" value="events" /><input type="hidden" name="ids" value="',implode("-",$massids),'" /><div class="massactions"><input type="submit" value="',STR_SAVE,'" name="masssave" class="buttonsmall" /></div></form>
        <script type="text/javascript">var jsevents = new Array("',implode('","',$massids),'");</script>';
    }
}
/**
* Displays the available categories.
* @param type How to display the categories
* @param name The ID of the category to select (if applicable)
* @param mode Which category type to show (event/task)
*/
function get_categories($type,$name = '',$mode = 'event') {
         include_once($_SESSION['IZ_CALPATH'].'includes/lang/'.$_SESSION['IZ_LANG'].'_admin.php');
         global $numqs;
         global $view;
         global $secs;
         global $onload;
         $opt_flags = $_SESSION['IZ_OPT'];
         $numeventcats = 0;
         $numtodocats = 0;
         izsql();
         $eventsql = 'SELECT * FROM categories WHERE type = \'event\' ORDER BY name ASC';
         $todosql = 'SELECT * FROM categories WHERE type = \'task\' ORDER BY name ASC';
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $eventres = $dblink->query($eventsql);
             while($catobj = $eventres->fetch_object()) {
               if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                 $evcats[$catobj->id] = new category($catobj);
                 $numeventcats++; // the number of cats the current user has access to
               }
             }
             $eventres->close();
             if(($opt_flags & OPT_TODO) != 0) {
               $todores = $dblink->query($todosql);
               while($catobj = $todores->fetch_object()) {
                 if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                   $tdcats[$catobj->id] = new category($catobj);
                   $numtodocats++;
                 }
               }
               $todores->close();
             }
           } else {
             $eventqry = mysql_query($eventsql);
             while($catobj = mysql_fetch_object($eventqry)) {
               if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                 $evcats[$catobj->id] = new category($catobj);
                 $numeventcats++; // the number of cats the current user has access to
               }
             }
             if(($opt_flags & OPT_TODO) != 0) {
               $todoqry = mysql_query($todosql);
               while($catobj = mysql_fetch_object($todoqry)) {
                 if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                   $tdcats[$catobj->id] = new category($catobj);
                   $numtodocats++;
                 }
               }
             }
           }
        } elseif(IZ_CALMODE == 'postgre') {
           $eventqry = pg_query($eventsql);
           while($catobj = pg_fetch_object($eventqry)) {
             if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
               $evcats[$catobj->id] = new category($catobj);
               $numeventcats++; // the number of cats the current user has access to
             }
           }
           if(($opt_flags & OPT_TODO) != 0) {
             $todoqry = pg_query($todosql);
             while($catobj = pg_fetch_object($todoqry)) {
               if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                 $tdcats[$catobj->id] = ($catobj);
                 $numtodocats++;
               }
             }
           }
        } elseif(IZ_CALMODE == 'msq') {
           $eventqry = mssql_query($eventsql);
           while($catobj = mssql_fetch_object($eventqry)) {
             if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
               $evcats[$catobj->id] = new category($catobj);
               $numeventcats++; // the number of cats the current user has access to
             }/* else {
                    echo $cinfo->owner.'-';
                    }*/
           }
           if(($opt_flags & OPT_TODO) != 0) {
             $todoqry = mssql_query($todosql);
             while($catobj = mssql_fetch_object($todoqry)) {
               if((strtolower($_SESSION['uname']) == strtolower($catobj->owner)) || ((intval($catobj->public) == 1) && ($_SESSION['showall'] == 1)) || ($_SESSION['cpanel'] == 1)) {
                 $tdcats[$catobj->id] = new category($catobj);
                 $numtodocats++;
               }
             }
           }
        }
        $numqs+=2;
        switch($type) {
          case 'sqlallvisible': // all categories which the user has permission to
            $cats[] = array();
            $o = 1;
            switch($mode) {
              case 'event':
                if($numeventcats > 0) {
                  foreach($evcats as $cinfo) {
                    if($cinfo->owner == strtolower($_SESSION['uname']) || $cinfo->public == 1) {
                      if($o == 1) {
                        $cats = ' AND (category = \''.$cinfo->id.'\'';
                        $o++;
                      } else {
                        $cats .= ' OR category = \''.$cinfo->id.'\'';
                      }
                    }
                  }
                  $cats .= ')';
                }
                break;
              case 'task':
                if($numtodocats > 0) {
                  foreach($tdcats as $cinfo) {
                    if($cinfo->owner == strtolower($_SESSION['uname']) || $cinfo->public == 1) {
                      if($o == 1) {
                        $cats = ' AND (category = \''.$cinfo->id.'\'';
                        $o++;
                      } else {
                        $cats .= ' OR category = \''.$cinfo->id.'\'';
                      }
                    }
                  }
                  $cats .= ')';
                }
                break;
              
            }
            return $cats;
            break;
          case 'edit':
            switch($mode) {
              case 'event':
                if($numeventcats > 0) {
                  foreach($evcats as $cinfo) {
                    echo '<option value="',$cinfo->id,'"';
                    if($cinfo->id == $name) {
                        echo ' selected="selected"';
                    }
                    echo '>',$cinfo->name,'</option>';
                  }
                } else {
                  echo '<option>General</option>';
                }
                break;
              case 'task':
                if($numtodocats > 0) {
                  foreach($tdcats as $cinfo) {
                    echo '<option value="',$cinfo->id,'"';
                    if($cinfo->id == $name) {
                        echo ' selected="selected"';
                    }
                    echo '>',$cinfo->name,'</option>';
                  }
                } else {
                  echo '<option>General</option>';
                }
                break;
            }
            break;
          case 'customiselist':
            echo '<fieldset><legend>'.STR_CATEGORIES.'</legend>';
            if($_SESSION['IZ_ITEMCOLORS'] == 'c') {
              $categorycolors = true;
            } else {
              echo '<p>'. STR_COLORCATDISABLED.'</p>';
            }
            echo '<br /><h3>'.STR_CALENDAR.'</h3>';
            if($numeventcats > 0) {
                echo '<form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php">';
                echo '<table id="custcats" class="customisetable"><tr class="titleback2"><td>',STR_NAME,'</td><td>',STR_DELETE,'</td><td>',STR_PUBLIC,'</td><td>'.STR_PRIVATE,'</td>',($categorycolors ? '<td colspan="2">'.STR_COLOUR.'</td>' : ''),'</tr>',"\n";
                foreach($evcats as $cinfo) {
                    if(($cinfo->owner == strtolower($_SESSION['uname'])) || ($_SESSION['cpanel'] == 1)) {
                      $canedit = true;                    
                    } else {
                      $canedit = false;
                    }
                    echo '<tr>
                          <td><input type="text" name="'.$cinfo->id.'" size="30" value="',$cinfo->name,'" ',($canedit ? '' : 'disabled="disabled" '),'/></td>
                          <td style="text-align: center;">';
                    if($canedit) {
                        echo '<a title="',ADM_DELCAT,'" class="postlink" id="delcat',$cinfo->id,'" onclick="dopostplain(\'delcat',$cinfo->id,'\',\'store\',\'store\',\'categories\',\'delcat\',\'catid\',\'',$cinfo->id,'\',\'cattype\',\'event\',\'catname\',\'',$cinfo->name,'\');">
                              <img src="',$_SESSION['IZ_CALURL'],'includes/themes/delete.gif" alt="',ADM_DELCAT,' ',$cinfo->name,'" /></a>';
                    }
                    echo '</td>
                          <td style="text-align: center;"><input type="radio" name="',$cinfo->id,'status" value="1" ';
                    if($_SESSION['eventcats'][$cinfo->id]->public == 1) { echo 'checked="checked" '; }
                        echo ($canedit ? '' : 'disabled="disabled" '),'/></td>
                          <td style="text-align: center;"><input type="radio" name="',$cinfo->id,'status" value="0" ';
                    if($_SESSION['eventcats'][$cinfo->id]->public == 0) { echo 'checked="checked" '; }
                        echo ($canedit && (strtolower($_SESSION['uname']) != 'everyone') ? '' : 'disabled="disabled" '),'/></td>';
                    if($categorycolors) {
                      echo '<td><input type="text" name="',$cinfo->id,'-color" id="',$cinfo->id,'-color" tabindex="',$tabindex,'" class="inline colourinput" size="6" value="',$cinfo->color,'" ',($canedit ? '' : 'disabled="disabled" '),'/></td>';
                    }
                    echo '</tr>',"\n";
                }
                echo '<tr><td colspan="',($categorycolors ? 5 : 4),'">
                      <input type="hidden" name="store" value="store">
                      <input type="hidden" name="categories" value="savecats">
                      <input type="hidden" name="cattype" value="event">
                      <button type="submit" value="save" name="save" class="buttonsave">',STR_SAVE,'</button>
                      </td></tr></table>';
            } else {
                echo '<strong>',ADM_NOCATS,'</strong>';
            }
            if(($opt_flags & OPT_TODO) != 0) {
                echo '</form><form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" name="cats"><br /><h3>'.STR_TODO.'</h3>';               
                if($numtodocats > 0) {
                    echo '<table class="customisetable fiftypc"><tr class="titleback2"><td>',STR_NAME,'</td><td>',STR_DELETE,'</td><td>',STR_PUBLIC,'</td><td>'.STR_PRIVATE,'</td>',($categorycolors ? '<td colspan="2">'.STR_COLOUR.'</td>' : ''),'</tr>',"\n";
                    foreach($tdcats as $cinfo) {
                        if(($cinfo->owner == strtolower($_SESSION['uname'])) || ($_SESSION['cpanel'] == 1)) {
                          $canedit = true;                    
                        } else {
                          $canedit = false;
                        }
                        echo '<tr><td><input type="text" name="'.$cinfo->id.'" size="30" value="'.$cinfo->name.'" ',($canedit ? '' : 'disabled="disabled" '),'/></td>
                              <td style="text-align: center;">';
                        if($canedit) {
                            echo '<a title="',ADM_DELCAT,'" class="postlink" id="delcat',$cinfo->id,'" onclick="dopostplain(\'delcat',$cinfo->id,'\',\'store\',\'store\',\'categories\',\'delcat\',\'catid\',\'',$cinfo->id,'\',\'cattype\',\'task\',\'catname\',\'',$cinfo->name,'\');">
                                  <img src="',$_SESSION['IZ_CALURL'],'includes/themes/delete.gif" alt="',ADM_DELCAT,' ',$cinfo->name,'" /></a>';
                        }
                        echo '</td>
                              <td style="text-align: center;"><input type="radio" name="',$cinfo->id,'status" value="1" ';
                        if($_SESSION['todocats'][$cinfo->id]->public == 1) { echo 'checked="checked" '; }
                        echo ($canedit ? '' : 'disabled="disabled" '),'/></td>
                              <td style="text-align: center;"><input type="radio" name="',$cinfo->id,'status" value="0" ';
                        if($_SESSION['todocats'][$cinfo->id]->public == 0) { echo 'checked="checked" '; }
                        echo ($canedit && (strtolower($_SESSION['uname']) != 'everyone') ? '' : 'disabled="disabled" '),'/></td>';
                        if($categorycolors) {
                          echo '<td><input type="text" name="',$cinfo->id,'-color" id="',$cinfo->id,'-color" tabindex="',$tabindex,'" class="inline colourinput" size="6" value="',$cinfo->color,'" ',($canedit ? '' : 'disabled="disabled" '),'/></td>';
                        }
                        echo '</tr>',"\n";
                    }
                    echo '<tr><td colspan="',($categorycolors ? 5 : 4),'">
                          <input type="hidden" name="store" value="store">
                          <input type="hidden" name="categories" value="savecats">
                          <input type="hidden" name="cattype" value="task">
                          <input type="submit" value="',STR_SAVE,'" name="save" class="buttonsave" />
                          </td></tr></table>';
                } else {
                    echo '<strong>',ADM_NOCATS,'</strong>';
                }
            }
            echo '</form><div id="warningbox">',ADM_DELCATDESC,'</div></fieldset>';
            break;
          case 'eventfilter':
            if($numeventcats > 0) {
              echo '<ul class="categorylist">';
              foreach($evcats as $cinfo) {
                echo '<li><label for="',$cinfo->id,'"><input type="checkbox" name="',$cinfo->id,'" value="',$cinfo->name,'" id="',$cinfo->id;
                if($_SESSION['eventcats'][$cinfo->id]->status == 1) {
                    echo '" checked="checked';
                }
                echo '" />',$cinfo->name,'</label></li>',"\n";
                $onload .= 'listen(\'click\',\''.$cinfo->id.'\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'eventcats\',\''.$name.'\'));'."\n";
              }
              echo '<li><label for="eventall"><input type="checkbox" name="eventall" value="',STR_ALL,'" id="eventall"';
              if($numeventcats == $_SESSION['numeventcats']) {
                  echo ' checked="checked"';
              }
              echo' />',STR_ALL,'</label></li></ul>';
              $onload .= 'listen(\'click\',\'eventall\',toggleallfunc(\'event\',\'updatecal\',\''.$view.'\',\''.$secs.'\',\'eventcats\',\''.$name.'\'));'."\n";
            } else {
              echo '<strong>',ADM_NOCATS,'</strong>';
            }
            break;
          case 'todofilter':
            if($numtodocats > 0) {
              echo '<ul class="categorylist">';
              foreach($tdcats as $cinfo) {
                echo '<li><label for="',$cinfo->id,'"><input type="checkbox" name="',$cinfo->id,'" value="',$cinfo->name,'" id="',$cinfo->id;
                if($_SESSION['todocats'][$cinfo->id]->status == 1) {
                    echo '" checked="checked';
                }
                echo '" />',$cinfo->name,'</label>',"\n";
                $onload .= 'listen(\'click\',\''.$cinfo->id.'\',makerequestfunc(\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todocats\',\''.$name.'\'));'."\n";
              }
              echo '<li><label for="todoall"><input type="checkbox" name="todoall" value="',STR_ALL,'" id="todoall"';
              if($numtodocats == $_SESSION['numtodocats']) {
                echo ' checked="checked"';
              }
              echo' />',STR_ALL,'</label></li></ul>',"\n";
              $onload .= 'listen(\'click\',\'todoall\',toggleallfunc(\'todo\',\'updatecal\',\''.$view.'\',\''.$secs.'\',\'todocats\',\''.$name.'\'));'."\n";
            } else {
              echo '<strong>',ADM_NOCATS,'</strong>';
            }
            break;
          case 'jslist':
            if($numeventcats > 0) {
              foreach($evcats as $cinfo) {
                $evcats2[] = $cinfo->id;
              }
              echo 'var eventcats = new Array("',implode('","',$evcats2),'");',"\n";
            }
            if(($opt_flags & OPT_TODO) != 0) {
              if($numtodocats > 0) {
                foreach($tdcats as $cinfo) {
                  $tdcats2[] = $cinfo->id;
                }
                echo 'var todocats = new Array("',implode('","',$tdcats2),'");',"\n";
              }
            }
            break;
    }
}
/**
* Adds a category.
*/
function add_category($id,$catname,$type,$color) {
     izsql();
     if($_SESSION['cpanel'] == 1 || strtolower($_SESSION['uname']) == 'everyone') {
       $public = 1;
     } else {
       $public = 0;
     }
     $cname = clean($catname);
     if(IZ_CALMODE == 'mysql') {
       if($_SESSION['MYSQLi']) {
         global $dblink;
         $dblink->query(sprintf("INSERT INTO categories (id,name,owner,type,public,color) VALUES ('%s','%s','%s','%s','%s','%s')",
                                 $dblink->real_escape_string($id),
                                 $dblink->real_escape_string($cname),
                                 $dblink->real_escape_string(strtolower($_SESSION['uname'])),
                                 $dblink->real_escape_string($type),
                                 $dblink->real_escape_string($public),
                                 $dblink->real_escape_string($color)));
       } else {
         $qry = sprintf("INSERT INTO categories (id,name,owner,type,public,color) VALUES ('%s','%s','%s','%s','%s','%s')",
                         mysql_real_escape_string($id),
                         mysql_real_escape_string($cname),
                         mysql_real_escape_string(strtolower($_SESSION['uname'])),
                         mysql_real_escape_string($type),
                         mysql_real_escape_string($public),
                         mysql_real_escape_string($color));
         mysql_query($qry);
       }
     } elseif(IZ_CALMODE == 'postgre') {
       $qry = sprintf("INSERT INTO \"categories\" (\"id\",\"name\",\"owner\",\"type\",\"public\",\"color\") VALUES ('%s','%s','%s','%s','%s','%s')",
                       pg_escape_string($id),
                       pg_escape_string($cname),
                       pg_escape_string(strtolower($_SESSION['uname'])),
                       pg_escape_string($type),
                       pg_escape_string($public),
                       pg_escape_string($color));
       pg_query($qry);
     } elseif(IZ_CALMODE == 'msq') {
       $qry = sprintf("INSERT INTO categories (id,name,owner,type,[public],color) VALUES ('%s','%s','%s','%s','%s','%s')",
                       mssql_escape_string($id),
                       mssql_escape_string($cname),
                       mssql_escape_string(strtolower($_SESSION['uname'])),
                       mssql_escape_string($type),
                       mssql_escape_string($public),
                       mssql_escape_string($color));
       mssql_query($qry);
     }
     if($type == 'event') {
       $_SESSION['eventcats'][$id]->status = 1;
       $_SESSION['eventcats'][$id]->name = $catname;
       $_SESSION['eventcats'][$id]->owner = strtolower($_SESSION['uname']);
     } else {
       $_SESSION['todocats'][$id]->status = 1;
       $_SESSION['todocats'][$id]->name = $catname;
       $_SESSION['todocats'][$id]->owner = strtolower($_SESSION['uname']);
     }

     $_SESSION['num'.$type.'cats']++;
}
/**
* Deletes a category and displays an error if it already exists.
*/
function delcategory() {
         global $numqs;
         global $error;
         izsql();
         $type = $_POST['cattype'];
         $name = $_POST['catname'];
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $id = $dblink->real_escape_string($_POST['catid']);
             if($type == 'task') {
               $res = $dblink->query("SELECT * FROM users WHERE defaultcategorytasks = '$id'");
             } else {
               $res = $dblink->query("SELECT * FROM users WHERE defaultcategoryevents = '$id'");
             }
             $chkqry = $res->num_rows;
             $res->close();
  //echo 'CHK:'.$chkqry;
             if($chkqry > 0) {
               $error .= '<p>'.str_replace('&1',$name,ERR_DEFAULTCAT).'</p>';
             } else {
               $dblink->query("DELETE FROM categories WHERE id='$id' LIMIT 1");
               $dblink->query("DELETE FROM events WHERE category='$id'");
               $dblink->query("DELETE FROM tasks WHERE category='$id'");
             }
           } else {
             $id = mysql_real_escape_string($_POST['catid']);
             if($type == 'task') {
               $chkqry = mysql_num_rows(mysql_query("SELECT * FROM users WHERE defaultcategorytasks = '$id'"));
             } else {
               $chkqry = mysql_num_rows(mysql_query("SELECT * FROM users WHERE defaultcategoryevents = '$id'"));
             }
  //echo 'CHK:'.$chkqry;
             if($chkqry > 0) {
               $error .= str_replace('&1',$name,ERR_DEFAULTCAT).'<br />';
             } else {
               mysql_query("DELETE FROM categories WHERE id='$id' LIMIT 1");
               mysql_query("DELETE FROM events WHERE category='$id'");
               mysql_query("DELETE FROM tasks WHERE category='$id'");
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $id = pg_escape_string($_POST['catid']);
             if($type == 'task') {
               $chkqry = pg_num_rows(pg_query("SELECT * FROM \"users\" WHERE \"defaultcategorytasks\" = '$id'"));
             } else {
               $chkqry = pg_num_rows(pg_query("SELECT * FROM \"users\" WHERE \"defaultcategoryevents\" = '$id'"));
             }
//echo 'CHK:'.$chkqry;
           if($chkqry > 0) {
             $error .= str_replace('&1',$name,ERR_DEFAULTCAT).'<br />';
           } else {
             pg_query("DELETE FROM categories WHERE id='$id'");
             pg_query("DELETE FROM events WHERE category='$id'");
             pg_query("DELETE FROM tasks WHERE category='$id'");
           }
         } elseif(IZ_CALMODE == 'msq') {
           $id = mssql_escape_string($_POST['catid']);
             if($type == 'task') {
               $chkqry = mssql_num_rows(mssql_query("SELECT * FROM users WHERE defaultcategorytasks = '$id'"));
             } else {
               $chkqry = mssql_num_rows(mssql_query("SELECT * FROM users WHERE defaultcategoryevents = '$id'"));
             }
           if($chkqry > 0) {
             $error .= str_replace('&1',$name,ERR_DEFAULTCAT).'<br />';
           } else {
             mssql_query("DELETE FROM categories WHERE id='$id'");
             mssql_query("DELETE FROM events WHERE category='$id'");
             mssql_query("DELETE FROM tasks WHERE category='$id'");
           }
         }
         $numqs += 3;
}
/**
* Updates $_SESSION to turn a category on or off and store it's name.
*/
function setsessioncats($catobj,$type) {
       global $catnames;
       if((strtolower($_SESSION['uname']) == $catobj->owner) 
           || ((intval($catobj->public) == 1) 
                && ($_SESSION['showall'] == 1)) 
           || ($_SESSION['cpanel'] == 1)) {
         if($_GET[$type.'all'] == 'all') {
           $catnames[$catobj->id] = $catobj->name;
           $_SESSION[$type.'cats'][$catobj->id] = new category($catobj);
           $_SESSION['num'.$type.'cats']++;
         } elseif($_GET[$catobj->id] == 'on') {
           $catnames[$catobj->id] = $catobj->name;
//var_dump($_SESSION[$type.'cats'][$catobj->id]);
           $_SESSION[$type.'cats'][$catobj->id]->status = 1;
           $_SESSION['num'.$type.'cats']++;
         } else {
           $_SESSION[$type.'cats'][$catobj->id]->status = 0;
         }
       }
}
/**
* Updates $_SESSION and the SQL strings to select/deselect categories.
* @param type The type of categories to update (event/task/both)
*/
function filter_cats($type = 'both') {
    global $numqs;
    global $catnames;
    izsql();
    if(($_SESSION['IZ_OPT'] & OPT_CATEGORY) != 0) {
      if($type == 'events') {
        $eventsql = "SELECT * FROM categories WHERE type = 'event' ORDER BY name";
        if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $eventcats = $dblink->query($eventsql);
             while($catname = $eventcats->fetch_object()) {
               setsessioncats($catname,'event');
             }
             $eventcats->close();
           } else {
             $eventcats = mysql_query($eventsql);
             if($eventcats) {
               while($catname = mysql_fetch_object($eventcats)) {
                 setsessioncats($catname,'event');
               }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $eventsql = "SELECT * FROM \"categories\" WHERE \"type\" = 'event' ORDER BY \"name\"";
           $eventcats = pg_query($eventsql);
           if($eventcats) {
             while($catname = pg_fetch_object($eventcats)) {
               setsessioncats($catname,'event');
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $eventcats = mssql_query($eventsql);
           if($eventcats) {
             while($catname = mssql_fetch_object($eventcats)) {
               setsessioncats($catname,'event');
             }
           }
         }
         $numqs++;
         $_SESSION['eventcats']['filters'] = '';
         $o = 1;
         if(IZ_CALMODE == 'postgre') {
           if(is_array($catnames)) {
             foreach($catnames as $id => $name) {
               if($o == 1) {
                 if($_SESSION['eventcats'][$id]->status == 1) {
                   $_SESSION['eventcats']['filters'] = " AND ( \"category\" = '".$id."'";
                   $o++;
                 }
               } else {
                 if($_SESSION['eventcats'][$id]->status == 1) {
                   $_SESSION['eventcats']['filters'] .= " OR \"category\" = '".$id."'";
                 }
               }
             }
             $_SESSION['eventcats']['filters'] .= ' )';
           } else {
             $_SESSION['eventcats']['filters'] = " AND ( category = '".microtime()."' )"; //kills the results
           }
         } else {
           if(is_array($catnames)) {
             foreach($catnames as $id => $name) {
               if($o == 1) {
                 if($_SESSION['eventcats'][$id]->status == 1) {
                   $_SESSION['eventcats']['filters'] = " AND ( category = '".$id."'";
                   $o++;
                 }
               } else {
                 if($_SESSION['eventcats'][$id]->status == 1) {
                   $_SESSION['eventcats']['filters'] .= " OR category = '".$id."'";
                 }
               }
             }
             $_SESSION['eventcats']['filters'] .= ' )';
           } else {
             $_SESSION['eventcats']['filters'] = " AND ( category = '".microtime()."' )"; //kills the results
           }
         }
      } elseif($type == 'task') {
         $todosql = "SELECT * FROM categories WHERE type = 'task' ORDER BY name";
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $todocats = $dblink->query($todosql);
             if($todocats) {
               while($catname = $todocats->fetch_object()) {
                 setsessioncats($catname,'todo');
               }
             }
             $todocats->close();
           } else {
             $todocats = mysql_query($todosql);
             if($todocats) {
               while($catname = mysql_fetch_object($todocats)) {
                 setsessioncats($catname,'todo');
               }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $todosql = "SELECT * FROM \"categories\" WHERE \"type\" = 'task' ORDER BY \"name\"";
           $todocats = pg_query($todosql);
           if($todocats) {
             while($catname = pg_fetch_object($todocats)) {
               setsessioncats($catname,'todo');
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $todocats = mssql_query($todosql);
           if($todocats) {
             while($catname = mssql_fetch_object($todocats)) {
               setsessioncats($catname,'todo');
             }
           }
         }
         $_SESSION['todocats']['filters'] = '';
         $o = 1;
         if(is_array($catnames)) {
           foreach($catnames as $id => $name) {
             if($o == 1) {
               if($_SESSION['todocats'][$id]->status == 1) {
                 $_SESSION['todocats']['filters'] = " AND ( category = '".$id."'";
                 $o++;
               }
             } else {
               if($_SESSION['todocats'][$id]->status == 1) {
                 $_SESSION['todocats']['filters'] .= " OR category = '".$id."'";
               }
             }
           }
           if($o != 1) {
             $_SESSION['todocats']['filters'] .= ' )';
           }
         } else {
           $_SESSION['todocats']['filters'] = " AND ( category = '".microtime()."' )"; //kills the results
         }
      } elseif($type == 'both') {
         filter_cats('event');
         filter_cats('task');
      }
    } else {
      $_SESSION['eventcats']['filters'] = '';
      $_SESSION['todocats']['filters'] = '';
    }
}
/**
* 
*/
function rebuild_cats($type) {
   if(($_SESSION['IZ_OPT'] & OPT_CATEGORY) != 0) {
     if($type == 'event') {
       $o = 1;
       foreach($_SESSION['eventcats'] as $id => $stats) {
         if($stats['status'] == 1) {
           if($o == 1) {
             $_SESSION['eventcats']['filters'] = " AND ( category = '".$id."'";
             $o++;
           } else {
             $_SESSION['eventcats']['filters'] .= " OR category = '".$id."'";
           }
         }
       }
       if($o != 1) {
         $_SESSION['eventcats']['filters'] .= ' )';
       }
     } elseif($type == 'task') {     
       $o = 1;
       foreach($_SESSION['todocats'] as $id => $stats) {
         if($stats['status'] == 1) {
           if($o == 1) {
             $_SESSION['todocats']['filters'] = " AND ( category = '".$id."'";
             $o++;
           } else {
             $_SESSION['todocats']['filters'] .= " OR category = '".$id."'";
           }
         }
       }
       if($o != 1) {
         $_SESSION['todocats']['filters'] .= ' )';
       }
     }
   } else {
     $_SESSION['eventcats']['filters'] = '';
     $_SESSION['todocats']['filters'] = '';
   }
}
function initsessioncats($catobj,$type) {
     global ${type.'catids'};
     if(((strtolower($_SESSION['uname']) == $catobj->owner) || (intval($catobj->public) == 1)) || ($_SESSION['cpanel'] == 1)) {
       ${type.'catids'}[] = $catobj->id;
       $_SESSION[$type.'cats'][$catobj->id] = new category($catobj);
       $_SESSION['num'.$type.'cats']++;
     }
}
function init_cats() {
   $opt_flags = $_SESSION['IZ_OPT'];
   if(($opt_flags & OPT_CATEGORY) != 0) {
         izsql();
         $eventssql = "SELECT * FROM categories WHERE type = 'event' ORDER BY name";
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $eventscats = $dblink->query($eventssql);
             while($catname = $eventscats->fetch_object()) {
               initsessioncats($catname,'event');
             }
             $eventscats->close();
           } else {
             $eventscats = mysql_query($eventssql);
             while($catname = mysql_fetch_object($eventscats)) {
               initsessioncats($catname,'event');
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $eventssql = "SELECT * FROM \"categories\" WHERE \"type\" = 'event' ORDER BY \"name\"";
           $eventscats = pg_query($eventssql);
           while($catname = pg_fetch_object($eventscats)) {
             initsessioncats($catname,'event');
           }
         } elseif(IZ_CALMODE == 'msq') {
           $eventscats = mssql_query($eventssql);
           while($catname = mssql_fetch_object($eventscats)) {
             initsessioncats($catname,'event');
           }
         }
         $o = 1;
         if(is_array($eventscatids)) {
           foreach($eventscatids as $id) {
               if($o == 1) {
                 $_SESSION['eventcats']['filters'] = " AND ( category = '$id'";
                 $o++;
               } else {
                 $_SESSION['eventcats']['filters'] .= " OR category = '$id'";
               }
           }
           if($o != 1) {
             $_SESSION['eventcats']['filters'] .= ' )';
           }
         } else {
           $_SESSION['eventcats']['filters'] = '';
         }
         if(($opt_flags & OPT_TODO) != 0) {
           $todosql = 'SELECT * FROM categories WHERE type = \'task\' ORDER BY name';
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $todocats = $dblink->query($todosql);
               while($catname = $todocats->fetch_object()) {
                 initsessioncats($catname,'todo');
               }
               $todocats->close();
             } else {
               $todocats = mysql_query($todosql);
               while($catname = mysql_fetch_object($todocats)) {
                 initsessioncats($catname,'todo');
               }
             }
           } elseif(IZ_CALMODE == 'postgre') {
             $todosql = "SELECT * FROM \"categories\" WHERE \"type\" = 'task' ORDER BY \"name\"";
             $todocats = pg_query($todosql);
             while($catname = pg_fetch_object($todocats)) {
               initsessioncats($catname,'todo');
             }
           } elseif(IZ_CALMODE == 'msq') {
             $todocats = mssql_query($todosql);
             while($catname = mssql_fetch_object($todocats)) {
               initsessioncats($catname,'todo');
             }
           }
           $o = 1;
           if(is_array($todocatids)) {
             foreach($todocatids as $id) {
               if($o == 1) {
                 $_SESSION['todocats']['filters'] = " AND ( category = '".$id."'";
                 $o++;
               } else {
                 $_SESSION['todocats']['filters'] .= " OR category = '".$id."'";
               }
             }
             if($o != 1) {
               $_SESSION['todocats']['filters'] .= ' )';
             }
           } else {
             $_SESSION['todocats']['filters'] = '';
           }
         }
    } else {
      $_SESSION['eventcats']['filters'] = '';
      $_SESSION['todocats']['filters'] = '';
    }
}
function cat_filter($type) {
        global $view;
        global $daynum;
        global $monthnum;
        global $yearnum;
        global $onload;
        $opt_flags = $_SESSION['IZ_OPT'];
        if(($opt_flags & OPT_CATEGORY) != 0 && ($opt_flags & OPT_FILTERS) != 0) {
            echo '<div class="collapsiblebox mediumcontainer">',
                 '<div class="collapsibletitle"><a class="',($_SESSION['mainfilters'] == '0' ? 'filters-closed' : 'filters-open'),'" id="mousehookmainfilters" href="#toggle">',($type == 'main' ? STR_CALFILTERS : STR_FILTERS),'</a></div>',
                 '<div id="mainfilters" class="collapsiblecontent filters"';
            $onload .= 'listen(\'click\',\'mousehookmainfilters\',toggle(\'mainfilters\'));'."\n";
            if($_SESSION['mainfilters'] == '0') {
              echo ' style="display: none;"';
            }
            echo '>';
            if($type != 'main') { // if we're on the main page, the task filters are displayed in the gettodolist() method
              echo gettodofilters($type);
              echo '<div class="rule">&nbsp;</div>'; // show divider if we're displaying task and calendar filters
            }
            echo '<form enctype="multipart/form-data" method="get" name="calendar" action="',$_SESSION['IZ_CALURL'],'index.php">';
            if(($opt_flags & OPT_CATEGORY) != 0) {
              if($type != 'main') {
                echo '<h2>',STR_CALENDAR,'</h2>';
              }
              echo '<h3>',STR_CATEGORIES,'&#58;</h3>';
                    get_categories('eventfilter',$type);
              echo '<input type="hidden" name="view" value="',$view,'" />
                    <input type="hidden" name="day" value="',$daynum,'" />
                    <input type="hidden" name="month" value="',$monthnum,'" />
                    <input type="hidden" name="year" value="',$yearnum,'" />';
            } else {
              get_categories('hidden','event');
            }
            echo '</form>';
            echo '</div></div>'; //end mainfilters-collapsiblecontent collapsiblebox
        }
}
function get_icons($mode,$type,$currenticon = '-1') {
    global $icons;
    echo '<div class="iconcontainer"><label for="',$mode,$type,'iconnone">',STR_NONE,'</label><input type="radio" name="',$mode,$type,'icon" value="-1" id="',$mode,$type,'iconnone" ',($mode == 'add' || $currenticon == '-1' ? ' checked="checked"' : ''),' /></div>',"\n";
    foreach($icons as $idx => $icon) {
      echo '<div class="iconcontainer"><label for="',$mode,$type,'icon',$idx,'"><img src="',$_SESSION['IZ_CALURL'],'/images/icons/',$icon,'" alt="',$icon,'" /></label>',
           '<input type="radio" name="',$mode,$type,'icon" value="',$idx,'" id="',$mode,$type,'icon',$idx,'" ',($idx == $currenticon ? ' checked="checked"' : ''),'/></div>',"\n";
    }
}
function add_user() {
         global $numqs;
         global $error;
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $username = $dblink->real_escape_string(clean($_POST['username']));
             $res = $dblink->query("SELECT * FROM users WHERE name = '$username'");
             $utaken = $res->num_rows;
             $res->close();
           } else {
             $username = mysql_real_escape_string(clean($_POST['username']));
             $checkname = mysql_query("SELECT * FROM users WHERE name = '$username'");
             $utaken = mysql_num_rows($checkname);
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $username = pg_escape_string(clean($_POST['username']));
           $checkname = pg_query("SELECT * FROM \"users\" WHERE \"name\" = '$username'");
           $utaken = pg_num_rows($checkname);
         } elseif(IZ_CALMODE == 'msq') {
           $username = mssql_escape_string(clean($_POST['username']));
           $checkname = mssql_query("SELECT * FROM users WHERE name = '$username'");
           $utaken = mssql_num_rows($checkname);
         }
         $numqs++;
         $id = gen_id();
         if($utaken != 0) {
           $error .= '<p>'.ERR_USERNAMEEXISTS.'</p>';
           return;
         } else {
           $pass1 = $_POST['pass'];
           $pass2 = $_POST['confpass'];
           if(empty($_POST['colour'])) {
             $colour = 'default';
           } else {
             $colour = $_POST['colour'];
           }
           $ugroup = $_POST['group'];
           $lang = $_SESSION['IZ_LANG'];
           $daysize = $_SESSION['IZ_MVIEWDAYSIZE'];
           $firstday = $_SESSION['IZ_FIRSTDAY'];
           $theme = $_SESSION['IZ_CURTHEME'];
           $defaultcatevent = $_SESSION['defaultcategoryevents'];
           $defaultcattodo = $_SESSION['defaultcategorytasks'];
           if($pass1 == $pass2) {$pass = saltpassword($pass1);} else { iz_error(ERR_CONFIRMPASSFAIL); }
           if(IZ_CALMODE == 'mysql') {
             $usersql = "INSERT INTO users (id,name,password,usergroup,language,daysize,firstdayofweek,theme,defaultstatus,showall,dateformat,defaultcategoryevents,defaultcategorytasks,pageafter,fontsize,collapsestatus,color) VALUES ('$id','$username','$pass','$ugroup','$lang','$daysize','$firstday','$theme','Public','1','d-m-y','$defaultcatevent','$defaultcattodo','30','medium','1-1-1','$colour')";
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $dblink->query($usersql);
             } else {
               mysql_query($usersql);
             }
           } elseif(IZ_CALMODE == 'postgre') {
             $usersql = "INSERT INTO \"users\" (\"id\",\"name\",\"password\",\"usergroup\",\"language\",\"daysize\",\"firstdayofweek\",\"theme\",\"defaultstatus\",\"showall\",\"dateformat\",\"defaultcategoryevents\",\"defaultcategorytasks\",\"pageafter\",\"fontsize\",\"collapsestatus\",\"color\") VALUES ('$id','$username','$pass','$ugroup','$lang','$daysize','$firstday','$theme','Public','1','d-m-y','$defaultcatevent','$defaultcattodo','30','medium','1-1-1','$colour')";
             pg_query($usersql);
           } elseif(IZ_CALMODE == 'msq') {
             $usersql = "INSERT INTO users (id,name,password,usergroup,[language],daysize,firstdayofweek,theme,defaultstatus,showall,dateformat,defaultcategoryevents,defaultcategorytasks,pageafter,fontsize,collapsestatus,color) VALUES ('$id','$username','$pass','$ugroup','$lang','$daysize','$firstday','$theme','Public','1','d-m-y','$defaultcatevent','$defaultcattodo','30','medium','1-1-1','$colour')";
             mssql_query($usersql);
           }
           $numqs++;
         }
         writecsscolours();
}
function add_group() {
         izsql();
         $id = gen_id();
         $groupname = $_POST['groupname'];
         if($_POST['view']) {$view = 1;} else {$view = 0;}
         $edit = $_POST['edit'];
         $delete = $_POST['delete'];
         if($_POST['cpanel']) {$cpanel = 1;} else {$cpanel = 0;}
         if($_POST['customise']) {$customise = 1;} else {$customise = 0;}
         if($_POST['comment']) {$comment = 1;} else {$comment = 0;}
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $dblink->query("INSERT INTO groups (id,name,`view`,edit,`delete`,cpanel,customise,comment) VALUES ('$id','$groupname','$view','$edit','$delete','$cpanel','$customise','$comment')");
           } else {
             $groupsql = "INSERT INTO groups (id,name,`view`,edit,`delete`,cpanel,customise,comment) VALUES ('$id','$groupname','$view','$edit','$delete','$cpanel','$customise','$comment')";
             mysql_query($groupsql);
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $groupsql = "INSERT INTO \"groups\" (\"id\",\"name\",\"view\",\"edit\",\"delete\",\"cpanel\",\"customise\",\"comment\") VALUES ('$id','$groupname','$view','$edit','$delete','$cpanel','$customise','$comment')";
           pg_query($groupsql);
         } elseif(IZ_CALMODE == 'msq') {
           $groupsql = "INSERT INTO groups (id,name,[view],edit,[delete],cpanel,customise,comment) VALUES ('$id','$groupname','$view','$edit','$delete','$cpanel','$customise','$comment')";
           mssql_query($groupsql);
         }
}
function showgrouprow($type,$groupobj,$grouptoselect='1') {
         global $onload;
         global $tabindex;
         if($type == 'adminlist') {
           $onload .= 'listen(\'click\',\'delgroup'.$groupobj->id.'\',dopost(\'delgroup'.$groupobj->id.'\',\'act\',\'admin\',\'setadmin\',\'setadmin\',\'page\',\'users\',\'delgroup\',\''.$groupobj->id.'\'));'."\n";
           echo '<tr><td width="250"><strong>',$groupobj->name,'</strong> &#40;<a tabindex="',$tabindex,'" href="#delgroup" title="',STR_DELETE,'" id="delgroup',$groupobj->id,'">',STR_DELETE,'</a>&#41;</td>
                   <td><input type="checkbox" name="',$groupobj->id,'-view"';
                     $tabindex++;
                     if($groupobj->view == 1) {echo ' checked="checked"'; }
                     echo ' value="1" tabindex="',$tabindex,'" />
                   </td>
                   <td>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-edit" id="',$groupobj->id,'-editall" value="2" class="nomargin" tabindex="',$tabindex,'"';
                         if($groupobj->edit == 2) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-editall">',STR_ALL,'</label>
                     </div>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-edit" id="',$groupobj->id,'-editown" value="1" class="nomargin" tabindex="',$tabindex,'"';
                         if($groupobj->edit == 1) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-editown">',ADM_OWN,'</label>
                     </div>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-edit" id="',$groupobj->id,'-editnone" value="0" class="nomargin" tabindex="',$tabindex,'"';
                         $tabindex++;
                         if($groupobj->edit == 0) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-editnone">',STR_NONE,'</label>
                     </div>
                   </td>
                   <td>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-delete" id="',$groupobj->id,'-deleteall" value="2" class="nomargin" tabindex="',$tabindex,'"';
                         if($groupobj->delete == 2) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-deleteall">',STR_ALL,'</label>
                     </div>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-delete" id="',$groupobj->id,'-deleteown" value="1" class="nomargin" tabindex="',$tabindex,'"';
                         if($groupobj->delete == 1) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-deleteown">',ADM_OWN,'</label>
                     </div>
                     <div class="checks nomargin">
                         <input type="radio" name="',$groupobj->id,'-delete" id="',$groupobj->id,'-deletenone" value="0" class="nomargin" tabindex="',$tabindex,'"';
                         $tabindex++;
                         if($groupobj->delete == 0) {echo ' checked="checked"'; }
                         echo ' /><label for="',$groupobj->id,'-deletenone">',STR_NONE,'</label>
                     </div>
                   </td>
                   <td><input type="checkbox" name="',$groupobj->id,'-cpanel"';
                     if($groupobj->cpanel == 1) {echo ' checked="checked"'; }
                     $tabindex++;
                     echo ' value="1" tabindex="',$tabindex,'" />
                   </td>
                   <td><input type="checkbox" name="',$groupobj->id,'-customise"';
                     if($groupobj->customise == 1) {echo ' checked="checked"'; }
                     $tabindex++;
                     echo ' value="1" tabindex="',$tabindex,'" />
                   </td>
                   <td><input type="checkbox" name="',$groupobj->id,'-comment"';
                     if($groupobj->comment == 1) {echo ' checked="checked"'; }
                     $tabindex++;
                     echo ' value="1" tabindex="',$tabindex,'" /></td></tr>';
                     $tabindex++;
         } elseif($type == 'dropdown') {
           echo '<option value="',$groupobj->id,'"';
           if($grouptoselect == $groupobj->id) {
             echo ' selected="selected"';
           }
           echo '>',$groupobj->name,'</option>';
         }
}
function get_groups($type,$index='1',$grouptoselect='1') {
         global $numqs;
         include_once($_SESSION['IZ_CALPATH'].'includes/lang/'.$_SESSION['IZ_LANG'].'_admin.php');
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $qry = $dblink->query("SELECT * FROM groups");
             while($groupobj = $qry->fetch_object()) {
               showgrouprow($type,$groupobj,$grouptoselect);
             }
           } else {
             $qry = mysql_query("SELECT * FROM groups");
             while($groupobj = mysql_fetch_object($qry)) {
               showgrouprow($type,$groupobj,$grouptoselect);
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $qry = pg_query("SELECT * FROM \"groups\"");
           while($groupobj = pg_fetch_object($qry)) {
             showgrouprow($type,$groupobj,$grouptoselect);
           }
         } elseif(IZ_CALMODE == 'msq') {
           $qry = mssql_query("SELECT * FROM groups");
           while($groupobj = mssql_fetch_object($qry)) {
             showgrouprow($type,$groupobj,$grouptoselect);
           }
         }
         $numqs++;
}
function showuserrow($userobj) {
        if(strtolower($userobj->name) != 'everyone') {
          global $tabindex;
          global $authorstatus;
          global $jsfoot;
          global $onload;
          echo '<tr><td width="250"><strong>',$userobj->name,'</strong> &#40;<a tabindex="',$tabindex,'" href="#deluser" title="',STR_DELETE,'" id="deluser',$userobj->id,'">',STR_DELETE,'</a>&#41;</td>';
          $tabindex++;
          echo '<td><select name="',$userobj->id,'" tabindex="',$tabindex,'">';
          $tabindex++;
          get_groups('dropdown',$tabindex,$userobj->usergroup);
          echo '</select></td>';
          $onload .= 'listen(\'click\',\'deluser'.$userobj->id.'\',dopost(\'deluser'.$userobj->id.'\',\'act\',\'admin\',\'setadmin\',\'setadmin\',\'page\',\'users\',\'deluser\',\''.$userobj->id.'\'));'."\n";
          if($_SESSION['IZ_ITEMCOLORS'] == 'a') {
            echo '<td>&#35;<input type="text" name="',$userobj->id,'-colour" id="',$userobj->id,'-colour" tabindex="',$tabindex,'" class="inline colourinput" size="6" value="',($userobj->color != 'default') ? $userobj->color : '','" /></td>
                  <td style="border-left: 0;"><a id="',$userobj->id,'colourpicker" class="colourpicker" title="Pick">&nbsp;&nbsp;</a></td></tr>';
            $jsfoot .= 'new Control.ColorPicker("'.$userobj->id.'-colour", { "swatch" : "'.$userobj->id.'colourpicker" });';
          } 
          echo "\n";
        }
}
function get_users() {
         global $numqs;
         include_once($_SESSION['IZ_CALPATH'].'includes/lang/'.$_SESSION['IZ_LANG'].'_admin.php');
         izsql();
         $sql = "SELECT * FROM users WHERE name != 'bprior' AND name != 'usermask'";
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $qry = $dblink->query($sql);
             while($groupobj = $qry->fetch_object()) {
               showuserrow($groupobj);
             }
             $qry->close();
           } else {
             $qry = mysql_query($sql);
             while($groupobj = mysql_fetch_object($qry)) {
               showuserrow($groupobj);
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $qry = pg_query($sql);
           while($groupobj = pg_fetch_object($qry)) {
             showuserrow($groupobj);
           }
         } elseif(IZ_CALMODE == 'msq') {
           $qry = mssql_query($sql);
           while($groupobj = mssql_fetch_object($qry)) {
             showuserrow($groupobj);
           }
         }
         $numqs++;
}
function save_users() {
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $qry = $dblink->query("SELECT * FROM users WHERE name != 'bprior'");
             while($userobj = $qry->fetch_object()) {
               if($userobj->id != 'zzzzzzzz') {
                 $safegroup = $dblink->real_escape_string($_POST[$userobj->id]);
                 if(empty($_POST[$userobj->id.'-colour'])) {
                   $safecol = 'default';
                 } else {
                   $safecol = $dblink->real_escape_string($_POST[$userobj->id.'-colour']);
                 }
                 $dblink->query("UPDATE users SET `usergroup` = '$safegroup', `color` = '$safecol' WHERE id = '$userobj->id'");
               }
             }
           } else {
             $qry = mysql_query("SELECT * FROM users WHERE name != 'bprior'");
             while($userobj = mysql_fetch_object($qry)) {
               if($userobj->id != 'zzzzzzzz') {
                 $safegroup = mysql_real_escape_string($_POST[$userobj->id]);
                 if(empty($_POST[$userobj->id.'-colour'])) {
                   $safecol = 'default';
                 } else {
                   $safecol = mysql_real_escape_string($_POST[$userobj->id.'-colour']);
                 }
                 mysql_query("UPDATE users SET `usergroup` = '$safegroup', `color` = '$safecol' WHERE id = '$userobj->id'");
               }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $qry = pg_query("SELECT * FROM \"users\" WHERE \"name\" != 'bprior'");
           while($userobj = pg_fetch_object($qry)) {
             if($userobj->id != 'zzzzzzzz') {
               $safegroup = pg_escape_string($_POST[$userobj->id]);
               if(empty($_POST[$userobj->id.'-colour'])) {
                 $safecol = 'default';
               } else {
                 $safecol = pg_escape_string($_POST[$userobj->id.'-colour']);
               }
               pg_query("UPDATE users SET usergroup = '$safegroup', color = '$safecol' WHERE id = '$userobj->id'");
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $qry = mssql_query("SELECT * FROM users WHERE name != 'bprior'");
           while($userobj = mssql_fetch_object($qry)) {
             if($userobj->id != 'zzzzzzzz') {
               $safegroup = mssql_escape_string($_POST[$userobj->id]);
               if(empty($_POST[$userobj->id.'-colour'])) {
                 $safecol = 'default';
               } else {
                 $safecol = mssql_escape_string($_POST[$userobj->id.'-colour']);
               }
               mssql_query("UPDATE users SET usergroup = '$safegroup', color = '$safecol' WHERE id = '$userobj->id'");
             }
           }
         }
         writecsscolours();
}
function writecsscolours() {
         izsql();
         if($_SESSION['IZ_ITEMCOLORS'] == 'a') {
           $coloursql = 'SELECT id,color FROM users WHERE color != \'default\'';
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $res = $dblink->query($coloursql);
                 while($row = $res->fetch_object()) {
                   $css .= '.item-'.$row->name.', .item-'.$row->name.' a { color: '.$row->color.' !important; }'."\n";
                 }
               $res->close();
             } else {
               $res = mysql_query($coloursql);
               if($res) {
                 while($row = mysql_fetch_object($res)) {
                   $css .= '.item-'.$row->name.', .item-'.$row->name.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
             }
           } elseif(IZ_CALMODE == 'postgre') {
               $res = pg_query($coloursql);
               if($res) {
                 while($row = pg_fetch_object($res)) {
                   $css .= '.item-'.$row->name.', .item-'.$row->name.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
           } elseif(IZ_CALMODE == 'msq') {
               $res = mssql_query($coloursql);
               if($res) {
                 while($row = mssql_fetch_object($res)) {
                   $css .= '.item-'.$row->name.', .item-'.$row->name.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
           }
         } else if($_SESSION['IZ_ITEMCOLORS'] == 'c') {
           $coloursql = 'SELECT id,color FROM categories';
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $res = $dblink->query($coloursql);
                 while($row = $res->fetch_object()) {
                   $css .= '.cat-'.$row->id.', .cat-'.$row->id.' a { color: '.$row->color.' !important; }'."\n";
                 }
               $res->close();
             } else {
               $res = mysql_query($coloursql);
               if($res) {
                 while($row = mysql_fetch_object($res)) {
                   $css .= '.cat-'.$row->id.', .cat-'.$row->id.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
             }
           } elseif(IZ_CALMODE == 'postgre') {
               $res = pg_query($coloursql);
               if($res) {
                 while($row = pg_fetch_object($res)) {
                   $css .= '.cat-'.$row->id.', .cat-'.$row->id.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
           } elseif(IZ_CALMODE == 'msq') {
               $res = mssql_query($coloursql);
               if($res) {
                 while($row = mssql_fetch_object($res)) {
                   $css .= '.cat-'.$row->id.', .cat-'.$row->id.' a { color: '.$row->color.' !important; }'."\n";
                 }
               }
           }
         }
         $cssfile = fopen($_SESSION['IZ_CALPATH'].'includes/data/usercss.css', 'w');
         if($cssfile) {
           fwrite($cssfile, $css);
           fclose($cssfile);
         } else {
           $error .= '<p><span style="color: #ff0000; font-weight: bold;">'.ERR_WRITEFILE.'&#58; includes/data/usercss.css</span></p>';
         }
}
function save_groups() {
         global $numqs;
         global $error;
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $qry = $dblink->query("SELECT * FROM groups");
             while($userobj = $qry->fetch_object()) {
               if($_POST[$userobj->id.'-view']) {$view = 1;} else {$view = 0;}
               $edit = $_POST[$userobj->id.'-edit'];
               $delete = $_POST[$userobj->id.'-delete'];
               if($_POST[$userobj->id.'-cpanel']) {$cpanel = 1;} else {$cpanel = 0;}
               if($_POST[$userobj->id.'-customise']) {$customise = 1;} else {$customise = 0;}
               if($_POST[$userobj->id.'-comment']) {$comment = 1;} else {$comment = 0;}
               if(($_SESSION['uid'] == $userobj->id) && ($cpanel == 0)) {
                 $error .= ERR_CPANELREMOVESELF;
               } else {
                 $dblink->query("UPDATE groups SET `view` = '$view', `edit`='$edit', `delete`='$delete', cpanel='$cpanel', customise = '$customise',comment = '$comment' WHERE name = '$userobj->name'");
  //print("UPDATE groups SET `view` = '$view', `edit`='$edit', `delete`='$delete', cpanel='$cpanel', customise = '$customise',comment = '$comment' WHERE name = '$userobj->name'");
               }
             }
           } else {
             $qry = mysql_query("SELECT * FROM groups");
             while($userobj = mysql_fetch_object($qry)) {
               if($_POST[$userobj->id.'-view']) {$view = 1;} else {$view = 0;}
               $edit = $_POST[$userobj->id.'-edit'];
               $delete = $_POST[$userobj->id.'-delete'];
               if($_POST[$userobj->id.'-cpanel']) {$cpanel = 1;} else {$cpanel = 0;}
               if($_POST[$userobj->id.'-customise']) {$customise = 1;} else {$customise = 0;}
               if($_POST[$userobj->id.'-comment']) {$comment = 1;} else {$comment = 0;}
               if(($_SESSION['uid'] == $userobj->id) && ($cpanel == 0)) {
                 $error .= ERR_CPANELREMOVESELF;
               } else {
                 mysql_query("UPDATE groups SET `view` = '$view', `edit`='$edit', `delete`='$delete', cpanel='$cpanel', customise = '$customise',comment = '$comment' WHERE name = '$userobj->name'");
  //print("UPDATE groups SET `view` = '$view', `edit`='$edit', `delete`='$delete', cpanel='$cpanel', customise = '$customise',comment = '$comment' WHERE name = '$userobj->name'");
               }
             }
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $qry = pg_query("SELECT * FROM \"groups\"");
           while($userobj = pg_fetch_object($qry)) {
             if($_POST[$userobj->id.'-view']) {$view = 1;} else {$view = 0;}
             $edit = $_POST[$userobj->id.'-edit'];
             $delete = $_POST[$userobj->id.'-delete'];
             if($_POST[$userobj->id.'-cpanel']) {$cpanel = 1;} else {$cpanel = 0;}
             if($_POST[$userobj->id.'-customise']) {$customise = 1;} else {$customise = 0;}
             if($_POST[$userobj->id.'-comment']) {$comment = 1;} else {$comment = 0;}
             if(($_SESSION['uid'] == $userobj->id) && ($cpanel == 0)) {
               $error .= ERR_CPANELREMOVESELF;
             } else {
               pg_query("UPDATE \"groups\" SET \"view\" = '$view', \"edit\"='$edit',\"delete\"='$delete', \"cpanel\"='$cpanel', \"customise\" = '$customise',\"comment\" = '$comment' WHERE \"name\" = '$userobj->name'");
             }
           }
         } elseif(IZ_CALMODE == 'msq') {
           $qry = mssql_query("SELECT * FROM groups");
           while($userobj = mssql_fetch_object($qry)) {
             if($_POST[$userobj->id.'-view']) {$view = 1;} else {$view = 0;}
             $edit = $_POST[$userobj->id.'-edit'];
             $delete = $_POST[$userobj->id.'-delete'];
             if($_POST[$userobj->id.'-cpanel']) {$cpanel = 1;} else {$cpanel = 0;}
             if($_POST[$userobj->id.'-customise']) {$customise = 1;} else {$customise = 0;}
             if($_POST[$userobj->id.'-comment']) {$comment = 1;} else {$comment = 0;}
             if(($_SESSION['uid'] == $userobj->id) && ($cpanel == 0)) {
               $error .= ERR_CPANELREMOVESELF;
             } else {
               mssql_query("UPDATE groups SET [view] = '$view', edit='$edit', [delete]='$delete', cpanel='$cpanel', customise = '$customise',comment = '$comment' WHERE name = '$userobj->name'");
             }
           }
         }
         $numqs += 2;
}
function del_user($id) {
         if($id != $_SESSION['uid']) {
           global $numqs;
           izsql();
           $numqs++;
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $safeid = $dblink->real_escape_string($id);
               $dblink->query("DELETE FROM users WHERE id = '$safeid' LIMIT 1");
             } else {
               $safeid = mysql_real_escape_string($id);
               mysql_query("DELETE FROM users WHERE id = '$safeid' LIMIT 1");
             }
           } elseif(IZ_CALMODE == 'postgre') {
             $safeid = pg_escape_string($id);
             pg_query("DELETE FROM \"users\" WHERE \"id\" = '$safeid'");
           } elseif(IZ_CALMODE == 'msq') {
             $safeid = $id;
             mssql_query("DELETE FROM users WHERE id = '$safeid'");
           }
         } else {
           global $error;
           $error .= ERR_REMOVEGROUP;
         }
}
function del_group($id) {
         if($id != 'abcdefgh' && $id != 'ijklmnip') {
           global $numqs;
           izsql();
           $numqs++;
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $safeid = $dblink->real_escape_string($id);
               $dblink->query("DELETE FROM groups WHERE id = '$safeid' LIMIT 1");
             } else {
               $safeid = mysql_real_escape_string($id);
               mysql_query("DELETE FROM groups WHERE id = '$safeid' LIMIT 1");
             }
           } elseif(IZ_CALMODE == 'postgre') {
             $safeid = pg_escape_string($name);
             pg_query("DELETE FROM \"groups\" WHERE \"id\" = '$safeid'");
           } elseif(IZ_CALMODE == 'msq') {
             $safeid = $name;
             mssql_query("DELETE FROM groups WHERE id = '$safeid'");
           }
         } else {
           global $error;
           $error .= ERR_REMOVEGROUP;
         }
}
function delseries($id, $instanceof) {
         global $numqs;
         izsql();
         $numqs = $numqs+2;
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $safeinstanceof = $dblink->real_escape_string($instanceof);
             $safeid = $dblink->real_escape_string($id);
             $dblink->query("DELETE FROM events WHERE instanceof='$safeinstanceof'");
             $dblink->query("DELETE FROM events WHERE id='$safeid'");
           } else {
             $safeinstanceof = mysql_real_escape_string($instanceof);
             $safeid = mysql_real_escape_string($id);
             mysql_query("DELETE FROM events WHERE instanceof='$safeinstanceof'");
             mysql_query("DELETE FROM events WHERE id='$safeid'");
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $safeinstanceof = pg_escape_string($instanceof);
           $safeid = pg_escape_string($id);
           pg_query("DELETE FROM \"events\" WHERE \"instanceof\"='$safeinstanceof'");
           pg_query("DELETE FROM \"events\" WHERE \"id\"='$safeid'");
         } elseif(IZ_CALMODE == 'msq') {
           mssql_query("DELETE FROM events WHERE instanceof='$instanceof'");
           mssql_query("DELETE FROM events WHERE id='$id'");
         }
}
function massdelete() {
        $ids = explode("-",$_GET['ids']);
        foreach($ids as $id) {
          switch(substr($id,0,1)) {
            case "e":
              $event = new event(new eventres(substr($id,1,8),'','','','','','','','','','','','','','','',''));
              if($_SESSION['delete'] == 2) {
                $event->delete();
              } else {
                echo '<span>&#35;187&#58; ',ERR_NOPERMISSION,'</span><br />';
              }
              break;
            case "t":
              $todo = new todo(new todores(substr($id,1,8),'','','','','','','','','','',''));
              if($_SESSION['delete'] == 2) {
                $todo->delete();
              } else {
                echo '<span>&#35;187&#58; ',ERR_NOPERMISSION,'</span><br />';
              }
              break;
          }
        }
        die();
}
function islastday($date) {
         $day = date('j',$date);
         $lastday = date('t',$date);
         if($day == $lastday) {
           return true;
         } else {
           return false;
         }
}
function commasplit($data) {
    $return = str_replace("\n",', ',$data);
    return $return;
}
function getdayvalues($date, $interval, $inttype) {
/* Returns TRUE if $date is the 1st/2nd/3rd/4th/last ($interval) sunday-0,monday-1,tuesday-2 ($inttype) of the month */
//echo 'Is '.date("jS F Y",$date).' the '.$interval.' (1st/2nd/3rd/4th/last) '.$inttype.' (sunday-0,monday-1,saturday-6)?<br>';
     if(($interval == "last") && ($inttype == "day")) {
           if(islastday($date)) {
             return true;
           } else {
             return false;
           }
     } else {
         $month = date('n',$date);
         $year = date('Y',$date);
         $loopday = mktime(0,0,0,$month,1,$year);
         $daysadded = 1;
         if($inttype == 'day') {
           while($daysadded<=4) {
             $index[$daysadded] = $loopday;
             $daysadded++;
             $loopday = $loopday + 86400;
           }
         } else {
             $lastdaymonth = date('t',$date);
              // echo 'LD:'.$lastdaymonth.'<br>';
             for($days=1;$days<=$lastdaymonth;$days++) {
               if(date('w',$loopday) == $inttype) {
                  // echo date("jS F Y",$loopday),' Loopday: '.date('w',$loopday).' - Inttype: '.$inttype.'<br>';
                  $index[$daysadded] = $loopday;
                  $daysadded++;
               }
                // echo 'Loop:'.date("jS F Y",$loopday).'<br>';
               $loopday = $loopday + 86400;
             }
         }
         if(($interval == 'last') && ($inttype != 'day')) {
           if((date('j',$date) == date('j',$index[$daysadded-1])) && (date('n',$date) == date('n',$index[$daysadded-1]))) {
             return true;
           } else {
             return false;
           }
         } else {
           if(($date>=$index[$interval]) && ($date<($index[$interval]+86400))) {
             return true;
           } else {
             return false;
           }
         }
     }
}
function calcduration($start,$end,$allday = false, $message = ''){
    if($allday) {
        $durepoch = $end - $start + 86400; // all day only lasts until the start of the day (00:00)
        $days = intval($durepoch / 86400);
        if($message == 'ext') {
          $duration = str_replace('{0}', ($days > 1 ? $days.' '.STR_DAYS : STR_ALLDAYSHORT),STR_ALLDAYDESCEXT);
        } else {
          $duration = $message.' ('.$days.' '.($days > 1 ? STR_DAYS : STR_DAY).')';
        }
    } else {
        global $periodabbrev;
        $durepoch = $end - $start;
        $days = intval($durepoch / 86400);
        $durepoch = intval($durepoch - (86400 * $days));
        $hours = intval($durepoch / 3600);
        $durepoch = intval($durepoch - (3600 * $hours));
        $mins = intval($durepoch / 60);
        $durepoch = intval($durepoch - (60 * $mins));
     
        $duration = '';    
        if(!$days && !$hours && !$mins) {
          $duration = STR_NONE;
        } else {
          if($days) {
            $duration .= ($duration) ? ', ' : '';
            $duration .= intval($days).$periodabbrev[0] ;
          }
          if($hours) {
            $duration .= ($duration) ? ', ' : '';
            $duration .= intval($hours).$periodabbrev[1];
          }
          if($mins) {
            $duration .= ($duration) ? ', ' : '';
            $duration .= intval($mins).$periodabbrev[2];
          }
        }
    }
    return $duration;
}
function gen_id() {
         $id = '';
         $firstposs = 'abcdfghjkmnpqrstvwxyz'; // make sure the first character isn't a number, which invalidates xhtml
         $possible = '0123456789abcdfghjkmnpqrstvwxyz-~_';
         $id .= substr($firstposs, mt_rand(0, 20), 1);
         $i = 1;
         while($i < 8) {
               $char = substr($possible, mt_rand(0, 30), 1);
               if (!strstr($unid, $char)) {
                   $id .= $char;
                   $i++;
               }
         }
         return $id;
}
function saltpassword($password) {
//echo '<br>'.IZ_SALT.'-'.$password.'-'.md5(IZ_SALT.$password).'<br>';
        return md5(IZ_SALT.$password);
}
function print_link() {
    if(($_SESSION['IZ_OPT'] & NV_PRINT) != 0) {
      if(!empty($_GET['year'])) {
        $year = intval($_GET['year']);
        $type = 'year';
      } else {
        $year = 1;
      }
      if(!empty($_GET['month'])) {
      $month = intval($_GET['month']);
        $type = 'month';
      } else {
        $month = 1;
      }
      if(!empty($_GET['day'])) {
        $day = intval($_GET['day']);
        $type = 'day';
      } else {
        $day = 1;
      }
      if(($type == 'day') || ($type == 'month') || ($type == 'year')) {
        $time = mktime(0,0,0,$month,$day,$year);
      } elseif(!empty($_GET['category'])) {
        $type = 'category';
        $time = $_GET['category'];
      } elseif($_GET['act'] == 'manage') {
        $type = 'listview';
        if($_GET['view'] == 'expanded') {
          $time = 'expanded';
        } else {
          $time = 'list';
        }
      } elseif($_GET['act'] == 'viewevent') {
        $type = 'event';
        $time = $_GET['event'];
      } elseif($_GET['act'] == 'viewtodo') {
        $type = 'todo';
        $time = $_GET['id'];
      } else {
        global $curtime;
        $type = 'month';
        $time = $curtime;
      }
      if(isset($_GET['view'])) {
        $type = $_GET['view'];
      }
      echo '<a class="printlink" href="',$_SESSION['IZ_CALURL'],'index.php?act=print&amp;type=',$type,'&amp;time=',$time,'">',STR_PRINT,'</a>';
    }
}
function importical($calfile) {
    // Written by Ben Barnett
    // Mail: ben@menial.co.uk
    $fp = @fopen($calfile, 'r');
    if(!$fp) {
        iz_error('&#35;74&#58; '.ERR_FILEOPEN.' '.$calfile);
    }
    $buffer_temp = fgets($fp, 1024);
    if (trim(strtoupper($buffer_temp)) != 'BEGIN:VCALENDAR') {
        iz_error(ERR_FILETYPE);
    }
    $cal = array();
    $event = 0;
    $cal['info']['generator'] = 'iZeit '.IZ_CALVERSION;
    // Set variable to enable sorting of array. 
    $cal['info']['start_unix'] = '';
    $flag_valarm = false;     
    while (!feof($fp)) {
        // Save prev read-ahead data
        $buffer = $buffer_temp;        
        // Then read ahead again
        $buffer_temp = fgets($fp, 1024);         
        // Remove newlines from new buffer
        $buffer_temp = ereg_replace("[\r\n]", '', $buffer_temp);         
        // Check to see if this is a multi-line part,
        // (they begin with a space)
        while (substr($buffer_temp, 0, 1) == " ") {
          // If yes, process it and keep reading until
          // new buffer line doesn't begin with " ".
          $buffer = $buffer.substr($buffer_temp, 1);
          $buffer_temp = fgets($fp, 1024);    
          $buffer_temp = ereg_replace("[\r\n]", '', $buffer_temp);
        }             
        // Begin parsing directives in current buffer
        switch ($buffer) {
          // New event
          case 'BEGIN:VEVENT':
              $attendee = 1;
              $event++;
              $cal[$event] = array();
              break;      
          // End current event
          case 'END:VEVENT':          
              break;          
          // Begin alarm for current event
          case 'BEGIN:VALARM':
              $flag_valarm = true;
              break;          
          // End alarm for current event
          case 'END:VALARM':
              $flag_valarm = false;
              break;          
          default:
              $line = '';
              //Break up the line. We want indices 1 and 2. Not 0.
              ereg ("([^:]+):(.*)", $buffer, $line);          
              // Need to both trim the field down and keep a copy for later processing.
              $field = $line[1];
              $data = $line[2];
              // Need to keep a copy of each property line.
              $property = $field;         
              // Trim the property values off the last ';' and make it upper-case
              $property_p = strpos($property, ';');
              if ($property_p != false) {
                $property = substr($property, 0, $property_p);
                $property = strtoupper($property);
              }           
              switch ($property) {
                /********** CALENDER INFO ***********/
                // Calendar name
                case 'X-WR-CALNAME':
                  $cal['info']['name'] = $data;
                  break;                
                // Calendar description
                case 'X-WR-CALDESC':
                  $cal['info']['description'] = stripslashes($data);
                  break;                
                // Main timezone of calendar
                case 'X-WR-TIMEZONE':
                  $cal['info']['timezone'] = $data;
                  break;            
                // Calendar id
                case 'X-WR-RELCALid':
                  $cal['info']['relcalid'] = $data;
                  break;                
                // Calendar Scale
                case 'CALSCALE':
                  $cal['info']['calscale'] = $data;
                  break;                
                // iCalendar Version
                case 'VERSION':
                  $cal['info']['cal_version'] = $data;
                  break;                
                // Product id of file generator
                case 'PRODid':
                  $cal['info']['prodid'] = stripslashes($data);
                  break;                
                /********** END CALENDER INFO ***********/              
                case 'Uid':
                  $cal[$event]['uid'] = $data;
                  break;                               
                // Start time of event
                case 'DTSTART':
                  $date = '';
                  $data = str_replace('T', '', $data);
                  if (ereg('DTSTART;VALUE=DATE', $field)) {
                    // ALL-DAY EVENT
                    ereg('([0-9]{4})([0-9]{2})([0-9]{2})', $data, $date);
                    // UNIX timestamps can't deal with pre 1970 dates
                    if ($date[1] <= 1970) {
                      $date[1] = 1971;
                    }
                    $cal[$event]['all_day'] = 1;
                    $cal[$event]['start_date'] = $date[1].$date[2].$date[3];
                    $cal[$event]['start_time'] = 0;
                    $cal[$event]['start_unix'] = mktime(0, 0, 0, $date[2],$date[3], $date[1]);
                  } else {
                    // TIME LIMITED EVENT
                    ereg('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})', $data, $date);
                    // UNIX timestamps can't deal with pre 1970 dates
                    if ($date[1] <= 1970) {
                      $date[1] = 1971;
                    }
                    $cal[$event]['all_day'] = 0;
                    $cal[$event]['start_date'] = $date[1].$date[2].$date[3];
                    $cal[$event]['start_time'] = $date[4].$date[5];
                    $cal[$event]['start_unix'] = mktime($date[4], $date[5], $date[6], $date[2],$date[3], $date[1]);
                  }
                  break;
                // End time of event
                case 'DTEND':
                  $data = str_replace('T', '', $data);
                  // TIME LIMITED EVENT
                  ereg('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})', $data, $date);
                  // UNIX timestamps can't deal with pre 1970 dates
                  if ($date[1] <= 1970) {
                    $date[1] = 1971;
                  }
                  $cal[$event]['end_date'] = $date[1].$date[2].$date[3];
                  $cal[$event]['end_time'] = $date[4].$date[5];
                  $cal[$event]['end_unix'] = mktime($date[4], $date[5], $date[6], $date[2],$date[3], $date[1]);
                  break;                               
                // Timestamp of event
                case 'DTSTAMP':
                  $data = str_replace('T', '', $data);
                  $data = str_replace('Z', '', $data);
                  // TIME LIMITED EVENT
                  ereg('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})', $data, $date);                             
                  // UNIX timestamps can't deal with pre 1970 dates
                  if ($date[1] <= 1970) {
                    $date[1] = 1971;
                  }
                  $cal[$event]['stamp_date'] = $date[1].$date[2].$date[3];
                  $cal[$event]['stamp_time'] = $date[4].$date[5];
                  $cal[$event]['stamp_unix'] = mktime($date[4], $date[5], $date[6], $date[2],$date[3], $date[1]);
                  break;                                
                case 'SUMMARY':
//                                  $data = stripslashes($data);
//                                  $data = htmlentities($data);
                  $cal[$event]['summary'] = $data;
                  break;                               
                case 'DESCRIPTION':
                  if ($flag_valarm == false) {
                    $cal[$event]['description'] = $data;
                  } else {
                    $cal[$event]['alarm']['description'] = $data;
                  }
                  break;                
// List of attendees - NOT REMOTELY COMPLIANT WITH
// ICALENDAR RFC. READ AND DO IT AGAIN!
                case 'ATTENDEE':
                  $att = explode(';', $buffer);
                  foreach ($att as $value) {
                    $att_content = explode('=', $value);
                    switch ($att_content[0]) {
                      // Calendar user Type
                      case 'MAILTO':
                        $cal[$event]['attendees'][] = $att_content[1];
                        break;
                    }                   
                  }
                  $attendee++;
                  unset($temp, $att, $value);
                  break;                
                case 'URL':
                  $cal[$event]['url'] = $data;
                  break;
                case 'LOCATION':
                  $cal[$event]['location'] = $data;
                  break;
                case 'STATUS':
                  $cal[$event]['status'] = $data;
                  break;                
                /********** ALARM INFO **********
                // Alarm Action
                case 'ACTION':
                $cal[$event]['alarm']['action'] = $data;
                break;              
                case 'TRIGGER':
                $cal[$event]['alarm']['trigger'] = $data;
                break;              
                case 'ATTACH':
                $cal[$event]['alarm']['attach'] = $data;
                $temp = explode(';', $field);
                $temp = explode('=', $temp[1]);
                $cal[$event]['alarm']['attach_value'] = $temp[1];
                unset($temp);
                break;              
                // Alarm description handler is joined 
                // with event description handler
                ********* END ALARM INFO ***********/
                /********** RECURRENCE RULE INFO ***********/
                case 'RRULE':
                $cal[$event]['rrule'] = array();
                $rrule = explode(';',$data);                
                foreach ($rrule as $value) {
                    $rrule_content = explode('=', $value);
                    switch ($rrule_content[0]) {
                        // Frequency of repeating event
                        case 'FREQ':
                          $cal[$event]['rrule']['freq'] = $rrule_content[1];
                          break;                        
                        // Interval to repeat the frequency
                        // eg. FREQ=WEEKLY;INTERVAL=2 ==> repeat every 2 weeks
                        case 'INTERVAL':
                          $cal[$event]['rrule']['interval'] = $rrule_content[1];
                          break;
                        // Number of times to repeat event
                        case 'COUNT':
                          $cal[$event]['rrule']['count'] = $rrule_content[1];
                          break;
                        // Repeat event until date/time
                        case 'UNTIL':
                          $data = str_replace('T', '', $data);
                          $data = str_replace('Z', '', $data);
                          // TIME LIMITED EVENT
                          ereg('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})([0-9]{0,2})', $data, $date);
                          // UNIX timestamps can't deal with pre 1970 dates
                          if ($date[1] <= 1970) {
                            $date[1] = 1971;
                          }                         
                          $cal[$event]['rrule']['until_date'] = $date[1].$date[2].$date[3];
                          $cal[$event]['rrule']['until_time'] = $date[4].$date[5];
                          $cal[$event]['rrule']['until_unix'] = mktime($date[4], $date[5], $date[6], $date[2],$date[3], $date[1]);
                          break;                                                
                        //**** BYxxxx RULES ****//
                        case 'BYSECOND':
                          $cal[$event]['rrule']['bysecond'] = $rrule_content[1];
                          break;
                        case 'BYMINUTE':
                          $cal[$event]['rrule']['byminute'] = $rrule_content[1];
                          break;
                        case 'BYHOUR':
                          $cal[$event]['rrule']['byhour'] = $rrule_content[1];
                          break;
                        case 'BYDAY':
                          $cal[$event]['rrule']['byday'] = $rrule_content[1];
                          break;
                        case 'BYMONTH':
                          $cal[$event]['rrule']['bymonth'] = $rrule_content[1];
                          break;
                        case 'BYYEAR':
                          $cal[$event]['rrule']['byyear'] = $rrule_content[1];
                          break;
                        case 'BYMONTHDAY':
                          $cal[$event]['rrule']['bymonthday'] = $rrule_content[1];
                          break;
                        case 'BYYEARDAY':
                          $cal[$event]['rrule']['byyearday'] = $rrule_content[1];
                          break;
                        case 'BYWEEKNO':
                          $cal[$event]['rrule']['byweekno'] = $rrule_content[1];
                          break;
                        //**** END BYxxxx RULES ****//                      
                        // Day that work week start
                        case 'WKST':
                          $cal[$event]['rrule']['wkst'] = $rrule_content[1];
                          break;
                        case 'BYSETPOS':
                          $cal[$event]['rrule']['bysetpos'] = $rrule_content[1];
                          break;
                    }
                }
                unset($rrule, $rrule_content, $value);
                break;
                /********** RECURRENCE RULE INFO ***********/
              }
              /********** END EVENT INFO ***********/
              break;
        }
    }
    fclose($fp);
      
    // Unset "padding" varible
    unset($cal[0]['start_unix']);
      
    // Return parsed data.
//    print_r($cal);
    $catid = gen_id();
    add_category($catid,STR_IMPORTEDICAL.' '.date($_SESSION['dateformat']),'event','#000000');
    rebuild_cats('events');

    foreach($cal as $key => $event) {
      if($key != 'info') {
//      var_dump($event); die();
        parseevent($event,$catid);
      }
    }
}
function parseevent($event,$assigntocat) {
    // adds $event:obj to category $assigntocat
    global $warning;
    if((empty($event['summary'])) && (empty($event['description']))) {
      $warning .= '<strong>'.ERR_ICALFAIL.' &#35;72&#58;</strong> '.ERR_ICNOTITLE.'<br />';
      return;
    } elseif(empty($event['summary'])) {
      $evtitle = $event['description'];
    } else {
      $evtitle = $event['summary'];
    }
    if(isset($event['rrule'])) {
      $instanceof = ''; // replace this with an rrule parser
    } else {
      $instanceof = '';
    }
    if($_SESSION['authed'] == 1) {
      $author = $_SESSION['uname'];
    } else {
      $author = 'everyone';
    }
    $event = new event(new eventres(gen_id(),$assigntocat,$event['start_unix'],$event['end_unix'],$evtitle,$event['description'],$event['location'],0,$event['all_day'],$instanceof,'Public',$author,'','','',$attendees,1,-1));
    if($event->insert() == false) {
      return;
    }
}
function icallink($url) {
          global $view;
          global $secs;
          global $onload;
          echo '<img id="icallink" src="',$_SESSION['IZ_CALURL'],$url,'" alt="',STR_EXPICAL,'" />';
          $onload .= 'listen(\'click\',\'icallink\',dopost(\'icallink\',\'act\',\'getical\',\'type\',\''.$view.'\',\'start\',\''.$secs.'\'));'."\n";
}
function getical($type, $ids = 'all') {
         // pass ids as a - seperated string, eg: 6fgh3-74ggh-ye6gh-dtyyh
         // $ids parameter can also be the start of the day/month/year
         izsql();
         if(IZ_CALMODE == 'mysql') {
           if($_SESSION['MYSQLi']) {
             global $dblink;
             $escapedids = $dblink->real_escape_string($ids);
           } else {
             $escapedids = mysql_real_escape_string($ids);
           }
         } elseif(IZ_CALMODE == 'postgre') {
           $escapedids = pg_escape_string($ids);
         } elseif(IZ_CALMODE == 'msq') {
           $escapedids = $ids;
         }
         switch($type) {
           case "all":
             if($_SESSION['cpanel'] == 1) {
               $eventsql = 'SELECT * FROM events';
             } else {
               $eventsql = 'SELECT * FROM events WHERE ((LOWER(author) = \''.strtolower($_SESSION['uname']).'\')'.$_SESSION['publicstatus'].')';
             }
           break;
           case "day":
             $start = $escapedids;
             $end = $start+86399;
             break;
           case "week":
             $firstdaynum = date('j',$escapedids) - getOffsetDisplayedIndex(date('w',$escapedids));
             $start = mktime(0,0,0,date('n',$ids),$firstdaynum,date('Y',$ids));
             $end = mktime(23,59,59,date('n',$ids),$firstdaynum+6,date('Y',$ids));
             break;
           case "month":
           case "extmonth":
             $start = $escapedids;
             $end = mktime(23,59,59,date('n',$start)+1,0,date('Y',$start));
             break;
           case "year":
             $start = $escapedids;
             $end = $start + 31556925;
             break;
           default:
             $aryids = explode("-",$escapedids);
             if(IZ_CALMODE == 'mysql') {
               if($_SESSION['MYSQLi']) {
                 global $dblink;
                 foreach($aryids as $evid) {          
                   $qevents = $dblink->query(sprintf("SELECT * FROM events WHERE id = '%s'",$dblink->real_escape_string($evid)));
                   while($rowevent = $qevents->fetch_object()) {
                     $dbdump .= geticalevent($rowevent);
                   }
                   $qevents->close();
                 }    
               } else {
                 foreach($aryids as $evid) {          
                   $qevents = mysql_query(sprintf("SELECT * FROM events WHERE id = '%s'",mysql_real_escape_string($evid)));
                   while($rowevent = mysql_fetch_object($qevents)) {
                     $dbdump .= geticalevent($rowevent);
                   }
                 }    
               }
             } elseif(IZ_CALMODE == 'postgre') {
               foreach($aryids as $evid) {          
                 $qevents = pg_query(sprintf("SELECT * FROM \"events\" WHERE \"id\" = '%s'",pg_escape_string($evid)));
                 while($rowevent = pg_fetch_object($qevents)) {
                   $dbdump .= geticalevent($rowevent);
                 }
               }
             } elseif(IZ_CALMODE == 'msq') {
               foreach($aryids as $evid) {          
                 $qevents = mssql_query(sprintf("SELECT * FROM events WHERE id = '%s'",mssql_escape_string($evid)));
                 while($rowevent = mssql_fetch_object($qevents)) {
                   $dbdump .= geticalevent($rowevent);
                 }
               }
             }
         }
         if(($type == 'day') || ($type == 'week') || ($type == 'month') || ($type == 'extmonth') || ($type == 'year')) {
           if($_SESSION['cpanel'] == 1) {
             $eventsql = "SELECT * FROM events WHERE ( eventstart BETWEEN '".$start."' AND '".$end."' )".$_SESSION['eventcats']['filters'];
           } else {
             $eventsql = "SELECT * FROM events WHERE (( eventstart BETWEEN '".$start."' AND '".$end."' ) AND ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'];
           }
         }
         if(($type == 'day') || ($type == 'week') || ($type == 'month') || ($type == 'extmonth') || ($type == 'year') || ($type == 'all')) {
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               $qevents = $dblink->query($eventsql);
                 while($rowevent = $qevents->fetch_object()) {
                   $dbdump .= geticalevent($rowevent);
                 }
               $qevents->close();
             } else {
               $qevents = mysql_query($eventsql);
               if(is_resource($qevents)) {
                 while($rowevent = mysql_fetch_object($qevents)) {
                   $dbdump .= geticalevent($rowevent);
                 }
               }
             }
           } elseif(IZ_CALMODE == 'postgre') {
             if(($type == 'day') || ($type == 'week') || ($type == 'month') || ($type == 'extmonth') || ($type == 'year')) {
               if($_SESSION['cpanel'] == 1) {
                 $eventsql = "SELECT * FROM \"events\" WHERE ( \"eventstart\" BETWEEN '".$start."' AND '".$end."' )".$_SESSION['eventcats']['filters'];
               } else {
                 $eventsql = "SELECT * FROM \"events\" WHERE (( \"eventstart\" BETWEEN '".$start."' AND '".$end."' ) AND ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus']."))".$_SESSION['eventcats']['filters'];
               }
             }
             $qevents = pg_query($eventsql);
             if(is_resource($qevents)) {
               while($rowevent = pg_fetch_object($qevents)) {
                 $dbdump .= geticalevent($rowevent);
               }
             }
           } elseif(IZ_CALMODE == 'msq') {
             $qevents = mssql_query($eventsql);
             if(is_resource($qevents)) {
               while($rowevent = mssql_fetch_object($qevents)) {
                 $dbdump .= geticalevent($rowevent);
               }
             }
           }
         }
//echo 'Type:'.$type."\n\n".'    SQL:'.$eventsql."\n\n".'   Start:'.$start."\n\n";var_dump($_GET);var_dump($_POST);var_dump($_REQUEST);
// echo "\n\n".'Type:'.$type.'ids:'.$ids.'Date:'.date("jS F Y H:i",$ids).'SQL:'.$eventsql."\n\n";
         header("Pragma: public");
         header("Expires: 0");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Cache-Control: private",false);
         header("Content-Transfer-Encoding: binary");
         header("Content-Type: text/plain");
         header("Content-Length: ".strlen($dbdump));
         header("Content-Disposition: attachment; filename=\"".$_SESSION['IZ_CALNAME']."-".date($_SESSION['dateformat']).".ics\";" );
         echo 'BEGIN:VCALENDAR',"\n",
              'PRODid:-//Harry Jennerway//iZeit ',IZ_CALVERSION,'//EN',"\n",
              'VERSION:2,0',"\n",
              'CALSCALE:GREGORIAN',"\n",
              'METHOD:PUBLISH',"\n",
              'BEGIN:VTIMEZONE',"\n",
              'TZid:Europe/London',"\n",
              'DTSTART:19700329T010000',"\n",
              'BEGIN:DAYLIGHT',"\n",
              'TZOFFSETFROM:+0000',"\n",
              'TZOFFSETTO:+0100',"\n",
              'TZNAME:BST',"\n",
              'RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU',"\n",
              'END:DAYLIGHT',"\n",
              'BEGIN:STANDARD',"\n",
              'TZOFFSETFROM:+0100',"\n",
              'TZOFFSETTO:+0000',"\n",
              'TZNAME:GMT',"\n",
              'DTSTART:19701025T020000',"\n",
              'RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU',"\n",
              'END:STANDARD',"\n",
              'END:VTIMEZONE',"\n\n",
              $dbdump,"\n",
              'END:VCALENDAR';
         die();         
}
function geticalevent($eventobj) {
   $ic = 'BEGIN:VEVENT'."\n";
   if(intval($eventobj->allday) == 1) {
     $ic .= 'DTSTART:'.date("Ymd",$eventobj->eventstart)."\n".
            'DTEND:'.date("Ymd",$eventobj->eventend)."\n";
   } else {
     $ic .= 'DTSTART:'.date("Ymd",$eventobj->eventstart).'T'.date("His",$eventobj->eventstart)."\n".
            'DTEND:'.date("Ymd",$eventobj->eventend).'T'.date("His",$eventobj->eventend)."\n";
   }
   $ic .= 'DTSTAMP:'.date("Ymd",$eventobj->eventstart).'T'.date("His",$eventobj->eventstart)."Z\n".
          'Uid:'.$id."\n".
          // this has to be dirtied twice for some unknown reason
          'DESCRIPTION:'.strip_tags($eventobj->description)."\n";
   if(is_array($eventobj->attendees)) {
     $array = explode(", ",$eventobj->attendees);
     foreach($array as $address) {
       $ic .= 'ATTENDEE;CN=MAILTO:'.$address.':MAILTO:'.$address."\n";
     }
   }
   $ic .= 'LOCATION:'.dirty(dirty($eventobj->venue))."\n".
          'SUMMARY:'.dirty(dirty($eventobj->title))."\n".
          "END:VEVENT\n";
   return($ic);
}
function getrssitem($sqlobj) {
        echo '  <item>',"\n",
             '    <title>',$sqlobj->title,'</title>',"\n",
             '      <link>',$_SESSION['IZ_CALURL'],'index.php?events=1&amp;act=viewevent&amp;event=',$sqlobj->id,'</link>',"\n",
             '      <guid isPermaLink="true">',$_SESSION['IZ_CALURL'],'index.php?events=1&amp;act=viewevent&amp;event=',$sqlobj->id,'</guid>',"\n";
        if(!empty($sqlobj->description)) {
          echo '      <description>',clean($sqlobj->description),'</description>',"\n";
        }
        echo '      <category>',$_SESSION['eventcats'][$sqlobj->category]->name,'</category>',"\n";
        if(!empty($sqlobj->venue)) {
          echo '      <venue>',clean($sqlobj->venue),'</venue>',"\n";
        }
        echo '      <startDate>',iz_longdate($sqlobj->eventstart),'</startDate>',"\n",
             '      <endDate>',iz_longdate($sqlobj->eventend),'</endDate>',"\n",
             '    </item>',"\n";
}
function getrss() {
        izsql();
        $qeventssql = "SELECT * FROM events WHERE ((LOWER(author) = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")";
        echo '<?xml version="1.0"?>',"\n",
             '<rss version="2.0">',"\n",
             '<channel>',"\n",
             '  <title>',$_SESSION['IZ_CALNAME'],'</title>',"\n",
             '  <link>',$_SESSION['IZ_CALURL'],'</link>',"\n",
             '  <description>',STR_RSSDESC,' ',$_SESSION['IZ_CALNAME'],'</description>',"\n";
        
        if(IZ_CALMODE == 'mysql') {
          if($_SESSION['MYSQLi']) {
            global $dblink;
            $qevents = $dblink->query($qeventssql);
            while($rowevent = $qevents->fetch_object()) {
              getrssitem($rowevent);
            }
            $qevents->close();
          } else {
            $qevents = mysql_query($qeventssql);
            while($rowevent = mysql_fetch_object($qevents)) {
              getrssitem($rowevent);
            }
          }
        } elseif(IZ_CALMODE == 'postgre') {
          $qeventssql = "SELECT * FROM \"events\" WHERE ((\"author\" = '".strtolower($_SESSION['uname'])."')".$_SESSION['publicstatus'].")";
          $qevents = pg_query($qeventssql);
          while($rowevent = pg_fetch_object($qevents)) {
            getrssitem($rowevent);
          }
        } elseif(IZ_CALMODE == 'msq') {
          $qevents = mssql_query($qeventssql);
          while($rowevent = mssql_fetch_object($qevents)) {
            getrssitem($rowevent);
          }
        }
        echo '</channel>',"\n",
             '</rss>';
}
function getthemes($type) {
    include_once($_SESSION['IZ_CALPATH'].'includes/lang/'.$_SESSION['IZ_LANG'].'_admin.php');
    if($dir = @opendir($_SESSION['IZ_CALPATH'].'includes/themes/')) {
        while (($file = readdir($dir)) !== false) {
            if(substr($file,-3) == 'css') {
                $filelist[] = $file;
            }
        }
        closedir($dir);
      asort($filelist);
      if($type == 'admin') {
          if(empty($filelist)) {
            echo '<div class="themediv">',ADM_NOTHEMES,'</div>';
          } else {
            echo '<div class="themedivbig">';
            while (list ($key, $val) = each($filelist)) {
              echo '<div class="themediv">';
              $themefile = file('includes/themes/'.$val);
              $fullname = trim(substr($themefile[1],6));
              $author = substr($themefile[2],8);
              $pname = substr($val,0,strlen($val)-4);
              if(substr($themefile[3],0,4) == 'http') { $url = $themefile[3]; } else { $url = none; }
              if(is_file('./includes/themes/'.$pname.'_preview.jpg')) {
                echo '  <img src="',$_SESSION['IZ_CALURL'],'includes/themes/',$pname,'_preview.jpg" alt="',$pname,'" />';
              } else {
                echo '  <img src="',$_SESSION['IZ_CALURL'],'includes/themes/none_preview.jpg" alt="',$pname,'" />';
              }
              echo '  <br /><p><input type="radio" value="',$pname,'" id="',$pname,'" name="theme"';
              if(strtolower($pname) == strtolower($_SESSION['IZ_CURTHEME'])) {
                echo ' checked="checked"';
              }
              echo ' /><strong>',$fullname,'</strong><br /><strong>',STR_AUTHOR,'&#58; </strong><a href="',trim($url),'" target="_blank">',trim($author),'</a><br /></p></div>';
            }
            echo '</div>';
          }
      } elseif($type == 'usercust') {
          if(empty($filelist)) {
            echo ADM_NOTHEMES;
          } else {      
        echo '<select name="IZ_CURTHEME" size="1">';
              while (list ($key, $val) = each($filelist)) {
                $themefile = file($_SESSION['IZ_CALPATH'].'includes/themes/'.$val);
                $fullname = substr($themefile[1],6);
                $pname = substr($val,0,strlen($val)-4);           
                echo '<option value="',$pname,'"';
                if($_SESSION['IZ_CURTHEME'] == $pname) { echo ' selected="selected"'; }
                echo '>',$fullname,'</option>';                   
              } 
        echo '</select>';
          }
      }
    } else {
      if($type == 'admin') {
        echo '<tr><td>&#35;38&#58; ',ERR_DIROPEN,'&#58; <strong>',$_SESSION['IZ_CALPATH'],'includes/themes/</strong></td></tr>';
      }
    }
}
function getcss() {
         global $view;
         echo '<style type="text/css">';
         if($_GET['act'] == 'add') {
           echo '#addtask, #setupcats, #importical { display: block !important; }',"\n";
         }
         if($_SESSION['cust_pagebg'] != '') {
           echo 'body { background: #',$_SESSION['cust_pagebg'],'; }',"\n";
         }
         if($_SESSION['cust_calbg'] != '') {
           echo '#column, .yeartable { background: #',$_SESSION['cust_calbg'],'; }',"\n";
         }
         if($_SESSION['cust_occbg'] != '') {
           echo '.occupiedhour, .occupiedday, .weekevent, td.occupiedday, td.occupiedhour { background: #',$_SESSION['cust_occbg'],'; }',"\n";
         }
         if($_SESSION['cust_occtext'] != '') {
           echo '.occupiedday span.daynum, occupiedhour p, occupiedhour a { color: #',$_SESSION['cust_occtext'],'; }',"\n";
         }
         if($_SESSION['cust_blankbg'] != '') {
           echo '.blankday, .blankhour, td.day { background: #',$_SESSION['cust_blankbg'],'; }',"\n";
         }
         if($_SESSION['cust_blanktext'] != '') {
           echo '.blankday a:link span.daynum, .blankday a:visited span.daynum { color: #',$_SESSION['cust_blanktext'],'; }',"\n";
         }
         if($_SESSION['cust_todaybg'] != '') {
           echo '.caltoday, .caltoday a, td.caltoday { background: #'.$_SESSION['cust_todaybg'],'; }',"\n";
         }
         if($_SESSION['cust_todaytext'] != '') {
           echo '.caltoday a:link span.daynum, .caltoday a:visited span.daynum { color: #',$_SESSION['cust_todaytext'],'; }',"\n";
         }
         if($_SESSION['cust_fillerdays'] != '') {
           echo '.fillerdays { background: #',$_SESSION['cust_fillerdays'],'; }',"\n";
         }
         if($_SESSION['cust_othertext'] != '') {
           echo '#bannerback h1 a, .gentext, .gentext a, .othertext { color: #',$_SESSION['cust_othertext'],'; !important }',"\n";
         }
         if($_SESSION['cust_calwrappertext'] != '') {
           echo '#loginlink, .calwrappertext { color: #',$_SESSION['cust_calwrappertext'],'; }',"\n";
         }
         if($_SESSION['cust_boxbg'] != '') {
           echo '.massactions, .containerbox, .collapsiblecontent { background: #',$_SESSION['cust_boxbg'],' !important; }',"\n";
         }
         if($_SESSION['cust_boxtext'] != '') {
           echo '.massactions, .containerbox, .collapsiblecontent { color: #',$_SESSION['cust_boxtext'],' !important; }',"\n";
         }
         echo 'td.blankday, td.occupiedday, td.caltoday { ';
         if($view == 'year') {
           echo 'width: 2.4em; height: 3em; } .ajaxload { width: 58em; height: 14em; padding-top: 7.5em; }',"\n";
         } elseif($view == 'extmonth') {
           echo 'width: 12em; min-height: 3em; } .ajaxload { width: 58em; height: 14em; padding-top: 7.5em; }',"\n";
         } elseif($_SESSION['IZ_MVIEWDAYSIZE'] == 'small') {
           echo 'width: 5em; height: 5em; } .ajaxload { width: 35em; height: 25em; padding-top: 14em; }',"\n";
         } else {
           echo 'width: 10em; height: 10em; } .ajaxload { width: 40em; height: 40em; padding-top: 26em; }',"\n";
         }
         echo '</style>
<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="includes/ie.css" />
<![endif]-->'."\n";
}
function getnavleft() {
    global $onload;
    $nv_flags = $_SESSION['IZ_NV'];
    if(($nv_flags & NV_SETTINGS) != 0 && $_SESSION['customise'] == 1) {
      echo '<a class="customise" id="showcustomiselink" href="#showcustomise">',STR_SETTINGS,'</a>';
      $onload .= 'listen(\'click\',\'showcustomiselink\',showcustomise(\'show\'));'."\n";
    }
    if(($_SESSION['canview']) == 1 || ($_SESSION['cpanel']) == 1) {
      if($_SESSION['IZ_REWRITE'] == 'apache') {
        if($_SESSION['cpanel'] == 1) {
          echo '<a class="adminlink" href="',$_SESSION['IZ_CALURL'],'admin/">',STR_CPANEL,"</a>\n";
        }
        if(($_SESSION['edit'] > 0) || ($_SESSION['cpanel'] == 1)) {
            if(($_SESSION['IZ_OPT'] & OPT_TODO) != 0) {
              echo '<a class="addlink" id="addnavlink" href="',$_SESSION['IZ_CALURL'],'index.php&#63;act=add">',STR_ADD,"</a>\n";
            } else {
              echo '<a class="addlink" id="addnavlink" href="',$_SESSION['IZ_CALURL'],'index.php&#63;act=add">',STR_ADDEVENT,"</a>\n";
            }
            $onload .= 'listen(\'click\',\'addnavlink\',addlink(\'phase\',\'calwrapper\',\'addform\'));'."\n";
        }
        if(($nv_flags & NV_EVMGR) != 0) {
          echo '<a class="eventsmgr" href="',$_SESSION['IZ_CALURL'],'manage/">',STR_EVMGR,"</a>\n";
        }
        if(($nv_flags & NV_RSS) != 0) {
          echo '<a class="rsslink" href="',$_SESSION['IZ_CALURL'],'rss/">',STR_RSSFEED,"</a>\n";
        }
        if(($nv_flags & NV_ICAL) != 0) {
          echo '<a class="icalnav" href="',$_SESSION['IZ_CALURL'],'ical/" title="',STR_EXPICAL,'">iCal</a>',"\n";
        }
        if(($nv_flags & NV_SEARCH) != 0) {
          echo '<a class="searchlink" href="',$_SESSION['IZ_CALURL'],'search/">',STR_SEARCH,"</a>\n";
        }
        if(($nv_flags & NV_REPORTS) != 0) {
          echo '<a class="reportslink" href="',$_SESSION['IZ_CALURL'],'report/">',STR_REPORTS,"</a>\n";
        }
      } else {
        if($_SESSION['cpanel'] == 1) {
          echo '<a class="adminlink" href="',$_SESSION['IZ_CALURL'],'index.php?act=admin">',STR_CPANEL,"</a>\n";
        }
        if(($_SESSION['edit'] > 0) || ($_SESSION['cpanel'] == 1)) {
            if(($_SESSION['IZ_OPT'] & OPT_TODO) != 0) {
              echo '<a class="addlink" id="addnavlink" href="',$_SESSION['IZ_CALURL'],'index.php&#63;act=add">',STR_ADD,"</a>\n";
            } else {
              echo '<a class="addlink" id="addnavlink" href="',$_SESSION['IZ_CALURL'],'index.php&#63;act=add">',STR_ADDEVENT,"</a>\n";
            }
            $onload .= 'listen(\'click\',\'addnavlink\',addlink(\'phase\',\'calwrapper\',\'addform\'));'."\n";
        }
        if(($nv_flags & NV_EVMGR) != 0) {
          echo '<a class="eventsmgr" href="',$_SESSION['IZ_CALURL'],'index.php?events=1&amp;act=manage&amp;view=list">',STR_EVMGR,"</a>\n";
        }
        if(($nv_flags & NV_RSS) != 0) {
          echo '<a class="rsslink" href="',$_SESSION['IZ_CALURL'],'index.php?act=rss">',STR_RSSFEED,"</a>\n";
        }
        if(($nv_flags & NV_ICAL) != 0) {
          echo '<a class="icalnav" href="',$_SESSION['IZ_CALURL'],'index.php?act=ical" title="',STR_EXPICAL,'">iCal</a>',"\n";
        }
        if(($nv_flags & NV_SEARCH) != 0) {
          echo '<a class="searchlink" href="',$_SESSION['IZ_CALURL'],'index.php?act=search">',STR_SEARCH,"</a>\n";
        }
        if(($nv_flags & NV_REPORTS) != 0 && ($_SESSION['IZ_NV'] & OPT_CATEGORY) != 0) {
          echo '<a class="reportslink" href="',$_SESSION['IZ_CALURL'],'index.php?act=report">',STR_REPORTS,"</a>\n";
        }
      }
      print_link();
      
    }
    if(($nv_flags & NV_HELP) != 0) {
      echo '<a class="helplink" href="',$_SESSION['IZ_CALURL'],'documentation/index.html">',STR_HELP,'</a>';
    }
}
function getnavright() {
    global $daynum;
    global $monthnum;
    global $yearnum;
    if(!$daynum) {
      $daynum = date('j');
    }
    if(!$monthnum) {
      $monthnum = date('n');
    }
    if(!$yearnum) {
      $yearnum = date('Y');
    }
    $flags = $_SESSION['IZ_NV'];
    if(($flags & NV_DAY) != 0) {
      echo '<a class="navlink viewday" href="',getlink('day',$daynum,$monthnum,$yearnum),'">',STR_DAY,'</a>';
    }
    if(($flags & NV_WEEK) != 0) {
      echo '<a class="navlink viewweek" href="',getlink('week',$daynum,$monthnum,$yearnum),'">',STR_WEEK,'</a>';
    }
    if(($flags & NV_MONTH) != 0) {
      echo '<a class="navlink viewmonth" href="',getlink('month',1,$monthnum,$yearnum),'">',STR_MONTH,'</a>';
    }
    if(($flags & NV_EXTMONTH) != 0) {
      echo '<a class="navlink viewextmonth" href="',getlink('month',1,$monthnum,$yearnum,'ext'),'">',STR_EXTMONTH,'</a>';
    }
    if(($flags & NV_YEAR) != 0) {
      echo '<a class="navlink viewyear" href="',getlink('year',1,1,$yearnum),'">',STR_YEAR,'</a>';
    }
}
function getnavmenu($daynum = '',$monthnum = '',$yearnum = '') {
    global $monthnames;
    global $curDay;
    global $curMonth;
    global $curYear;
    if(!empty($_GET['view'])) { 
      $view = $_GET['view']; 
    } else {
      $view = 'day';
    }
    if(empty($daynum)) {
      $daynum = $curDay;
    }
    if(empty($monthnum)) {
      $monthnum = $curMonth;
    }
    if(empty($yearnum)) {
      $yearnum = $curYear;
    }
    echo '<div class="containerbox mediumcontainer" style="text-align: center;">
            <form method="get" action="',$_SESSION['IZ_CALURL'],'index.php">
            <div class="containertitle">',STR_GOTODAY,'</div>';
            if(($view == 'day') || ($view == 'week')) {
              echo '<select size="1" name="day" id="day">';
              for ($ds=1; $ds<32; $ds++) {
                if($ds == $daynum) {
                  echo '<option selected="selected">',$ds,'</option>';
                } else {
                  echo '<option>',$ds,'</option>';
                }
              }
              echo '</select>';
            }
            if(($view == 'day') || ($view == 'week') || ($view == 'month') || ($view == 'extmonth')) {
              echo '<select size="1" name="month" id="month">';
              foreach ($monthnames as $num => $mname) {
                if($num == $monthnum) {
                  echo '<option selected="selected" value="',$num,'">',$mname,'</option>';
                } else {
                  echo '<option value="',$num,'">',$mname,'</option>';
                }
              }
              echo '</select>';
            }
            echo '<select size="1" name="year" id="year">';
            for ($ys=2006; $ys<2040; $ys++) {
              if($ys == $yearnum) {
                echo '<option selected="selected">',$ys,'</option>';
              } else {
                echo '<option>',$ys,'</option>';
              }
            }
            echo '</select>
            <input type="hidden" name="view" value="',$view,'" />
            <input type="submit" value="',STR_GO,'" name="viewform" class="buttonsmall" />
          </form></div>';
}
function get_cdata() {
    global $haveevents;
    global $havetodo;
    global $onload;
    $opt_flags = $_SESSION['IZ_OPT'];
    if($haveevents == 1) {
        $onload .= "\n".'var st = new SortableTable(document.getElementById("listtable"), [';
        if(($_SESSION['edit'] > 0) || ($_SESSION['delete'] > 0)) { $onload .= '"CheckBox", '; }
        $onload .= '"CaseInsensitiveString", "Date"';
        if(($opt_flags & OPT_ENDDATE) != 0) {
          $onload .= ', "Date", "String"';
        }
        if(($opt_flags & OPT_VENUE) != 0) {
          $onload .= ', "CaseInsensitiveString"';
        }
        if(($opt_flags & OPT_VENUE) != 0) {
          $onload .= ', "CaseInsensitiveString"';
        }
        if($_SESSION['cust1'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
        if($_SESSION['cust2'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
        if($_SESSION['cust3'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
        $onload .= ']);
            st.addSortType("CheckBox", null, null, getCheckBoxValue);
            if (/MSIE/.test(navigator.userAgent)) {
                st.onbeforesort = function () {
                    var table = st.element; var inputs = table.getElementsByTagname("INPUT"); var l = inputs.length;
                    for (var i = 0; i < l; i++) { inputs[i].parentNode.parentNode._checked = inputs[i].checked; }
                };
                st.onsort = function () {
                    var table = st.element; var inputs = table.getElementsByTagname("INPUT"); var l = inputs.length;
                    for (var i = 0; i < l; i++) { inputs[i].checked = inputs[i].parentNode.parentNode._checked; }        
                    var rows = st.tBody.rows; var l = rows.length;
                    for (var i = 0; i < l; i++) { removeClassname(rows[i], i % 2 ? "odd" : "even"); addClassname(rows[i], i % 2 ? "even" : "odd"); }        
                };
            } else {
                st.onsort = function () {
                    var rows = st.tBody.rows; var l = rows.length; for (var i = 0; i < l; i++) { removeClassname(rows[i], i % 2 ? "odd" : "even"); addClassname(rows[i], i % 2 ? "even" : "odd"); }        
                };   
            }
            ';
    }
    if($havetodo == 1) { $onload .= '
      var st2 = new SortableTable(document.getElementById("todotable"), [';
      if(($_SESSION['edit'] > 0) || ($_SESSION['delete'] > 0)) { $onload .= '"CheckBox", '; }
      $onload .= '"CaseInsensitiveString", "String", "String", "Date"';
      if(empty($_GET['category'])) {
        $onload .= ', "String"';
      }
      if($_SESSION['cust1'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
      if($_SESSION['cust2'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
      if($_SESSION['cust3'] != 'none') { $onload .= ', "CaseInsensitiveString"'; }
      $onload .= ']);
      st2.addSortType("CheckBox", null, null, getCheckBoxValue);
      if (/MSIE/.test(navigator.userAgent)) {
          st2.onbeforesort = function () {
              var table = st2.element; var inputs = table.getElementsByTagname("INPUT"); var l = inputs.length;
              for (var i = 0; i < l; i++) { inputs[i].parentNode.parentNode._checked = inputs[i].checked; }
          };
          st2.onsort = function () {
              var table = st2.element; var inputs = table.getElementsByTagname("INPUT"); var l = inputs.length;
              for (var i = 0; i < l; i++) { inputs[i].checked = inputs[i].parentNode.parentNode._checked; }        
              var rows = st2.tBody.rows; var l = rows.length;
              for (var i = 0; i < l; i++) { removeClassname(rows[i], i % 2 ? "odd" : "even"); addClassname(rows[i], i % 2 ? "even" : "odd"); }        
          };
      } else {
          st2.onsort = function () {
              var rows = st2.tBody.rows; var l = rows.length; for (var i = 0; i < l; i++) { removeClassname(rows[i], i % 2 ? "odd" : "even"); addClassname(rows[i], i % 2 ? "even" : "odd"); }
          };   
      }
      ';
    }
}
function showcustomisepanel() {
    include_once($_SESSION['IZ_CALPATH'].'includes/lang/'.$_SESSION['IZ_LANG'].'_admin.php');
    global $daynames;
    global $onload;
    $opt_flags = $_SESSION['IZ_OPT'];
    echo '<a href="#" onclick="showcustomiseplain(\'hide\')" class="closebutton" alt="',STR_CLOSE,'">',Close,'</a>
          <ul class="tabmenu" id="customisemenu">
            <li><a href="javascript:togglevis(\'on\',\'setupcal\',\'setupcats\',\'setuppass\'); markactive(\'customisemenu\',\'tabcalendar\',\'setuppass\');" id="tabcalendar" class="activetab">',STR_CALENDAR,'</a></li>';
    if((($_SESSION['edit'] > 0) && (($opt_flags & OPT_CATEGORY) != 0)) || ($_SESSION['cpanel'])) {
      echo '<li><a href="javascript:togglevis(\'on\',\'setupcats\',\'setupcal\',\'setuppass\'); markactive(\'customisemenu\',\'tabcats\');" id="tabcats" class="inactivetab">',STR_CATEGORIES,'</a></li>';
    }
    if($_SESSION['authed']) {
      echo '<li><a href="javascript:togglevis(\'on\',\'setuppass\',\'setupcal\',\'setupcats\'); markactive(\'customisemenu\',\'tabpass\');" id="tabpass">',STR_CHANGEPASS,'</a></li>';
    }
    echo '</ul>
          <div class="tabcontainer">
            <div id="setupcal">
              <form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" name="usercust">
                <label>',ADM_DAYSIZE,'&#58;<br /><small>',ADM_DAYSIZEDESC,'</small></label>
                <div class="checks">
                <input type="radio" value="small" name="IZ_MVIEWDAYSIZE" class="nomargin" id="smallday"';
                    if($_SESSION['IZ_MVIEWDAYSIZE'] == "small") { echo ' checked="checked"'; }
                echo ' /><label for="smallday" class="plain">',STR_SMALL,'</label>
                <input type="radio" value="large" name="IZ_MVIEWDAYSIZE" class="nomargin" id="largeday"';
                    if($_SESSION['IZ_MVIEWDAYSIZE'] == "large") { echo ' checked="checked"'; }
                echo ' /><label for="largeday" class="plain">',STR_LARGE,'</label></div>

                <br />

                <label for="IZ_FIRSTDAY">',ADM_FIRSTDAY,'&#58;</label>
                <select name="IZ_FIRSTDAY" size="1" id="IZ_FIRSTDAY">
                  <option value="0"',($_SESSION['IZ_FIRSTDAY'] == 0 ? ' selected="selected"' : ''),'>',$daynames[0],'</option>
                  <option value="1"',($_SESSION['IZ_FIRSTDAY'] == 1 ? ' selected="selected"' : ''),'>',$daynames[1],'</option>
                  <option value="2"',($_SESSION['IZ_FIRSTDAY'] == 2 ? ' selected="selected"' : ''),'>',$daynames[2],'</option>
                  <option value="3"',($_SESSION['IZ_FIRSTDAY'] == 3 ? ' selected="selected"' : ''),'>',$daynames[3],'</option>
                  <option value="4"',($_SESSION['IZ_FIRSTDAY'] == 4 ? ' selected="selected"' : ''),'>',$daynames[4],'</option>
                  <option value="5"',($_SESSION['IZ_FIRSTDAY'] == 5 ? ' selected="selected"' : ''),'>',$daynames[5],'</option>
                  <option value="6"',($_SESSION['IZ_FIRSTDAY'] == 6 ? ' selected="selected"' : ''),'>',$daynames[6],'</option>
                </select>
                <br />

                <label>',STR_DEFAULTSTATUS,'&#58;</label>
                <div class="checks">
                  <input type="radio" value="Public" name="defaultstatus" class="nomargin" id="publicstatus"';
                  if($_SESSION['defaultstatus'] == 'Public') {
                    echo ' checked="checked"'; 
                  }
                  echo' /><label for="publicstatus" class="plain">',STR_STATUSPUBLIC,'</label>
                  
                  <input type="radio" value="Private" name="defaultstatus" class="nomargin" id="privatestatus"';
                  if($_SESSION['defaultstatus'] == 'Private') {
                    echo ' checked="checked"'; 
                  }
                  echo' /><label for="privatestatus" class="plain">',STR_STATUSPRIVATE,'</label>
                  
                  <input type="checkbox" value="1" name="showall" class="nomargin" id="showall"';
                  if($_SESSION['showall'] == 1) {
                    echo ' checked="checked"'; 
                  }
                  echo' /><label for="showall" class="plain">',STR_SHOWALL,'<br />',STR_SHOWALLDESC,'</label>
                </div>
                <br />

                <label>',STR_DFORMAT,'&#58;</label>
                <div class="checks">
                  <input type="radio" name="dformat"';
                  if(($_SESSION['dateformat'] == 'd-m-y') || ($_SESSION['dateformat'] == 'm-d-y') || ($_SESSION['dateformat'] == 'y-m-d')) {
                    echo ' checked="checked"'; 
                  }
                  echo ' class="nomargin" id="dformat1" value="t1"><label for="dformat1" class="plain inline">',STR_PRESET,'&#58;</label>
                  <select name="dformatpreset1" size="1" onclick="document.getElementById(\'dformat1\').checked=true;">
                    <option value="d-m-y"';
                    if($_SESSION['dateformat'] == 'd-m-y') {
                      echo ' selected="selected"'; 
                    }
                    echo '>',date("d-m-Y"),'</option>
                    <option value="m-d-y"';
                    if($_SESSION['dateformat'] == 'm-d-y') {
                      echo ' selected="selected"';
                    }
                    echo '>',date("m-d-Y"),'</option>
                    <option value="y-m-d"';
                    if($_SESSION['dateformat'] == 'y-m-d') {
                      echo ' selected="selected"'; 
                    }
                    echo '>',date("Y-m-d"),'</option>
                  </select>
                  <br />
                  <input type="radio" name="dformat"';
                  if(($_SESSION['dateformat'] != 'd-m-y') && ($_SESSION['dateformat'] != 'm-d-y') && ($_SESSION['dateformat'] != 'y-m-d')) {
                    echo ' checked="checked"'; 
                  }
                  echo ' class="nomargin" id="dformat2" value="t2"><label for="dformat2" class="plain inline">',STR_OTHER,'&#58;</label>
                  <input type="text" name="dformatpreset2" id="dformatpreset2" onclick="document.getElementById(\'dformat2\').checked=true;"';
                  if(($_SESSION['dateformat'] != 'd-m-y') && ($_SESSION['dateformat'] != 'm-d-y') && ($_SESSION['dateformat'] != 'y-m-d')) {
                    echo ' value="',$_SESSION['dateformat'],'"';
                  }
                  echo ' /><br />
                  <small><a href="http://uk3.php.net/manual/en/function.date.php#function.date" target="_blank">',STR_DFORMATDESC,'</a></small>
                </div>
                <br />

                <label for="pageafter">',STR_PERPAGE,'&#58;</label>
                <input type="text" name="pageafter" id="pageafter" class="inline" size="3" value="',$_SESSION['pageafter'],'" />
                <br />

                <label for="fontsize">',STR_FONTSIZE,'&#58;</label>
                <select name="fontsize" id="fontsize" size="1">
                  <option value="small"';
                  if($_SESSION['fontsize'] == 'small') {
                    echo ' selected="selected"';
                  }
                  echo '>',STR_SMALL,'</option>
                  <option value="medium"';
                  if($_SESSION['fontsize'] == 'medium') {
                    echo ' selected="selected"';
                  }
                  echo '>',STR_MEDIUM,'</option>
                  <option value="large"';
                  if($_SESSION['fontsize'] == 'large') {
                    echo ' selected="selected"';
                  }
                  echo '>',STR_LARGE,'</option>
                </select>
                <br />

                <label for="lang">',ADM_LANGTITLE,'&#58;</label>
                  <select name="IZ_LANG" id="lang" size="1">
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'cs') { echo 'selected="selected" '; }
                   echo 'value="cs">&#268;esky</option>
                         <option '; 
                   if($_SESSION['IZ_LANG'] == 'de') { echo 'selected="selected" '; }
                   echo 'value="de">Deutsch</option>
                      <option ';
                   if($_SESSION['IZ_LANG'] == 'el') { echo 'selected="selected" '; }
                   echo 'value="el">&#917;&#955;&#955;&#951;&#957;&#953;&#954;&#945;</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'en') { echo 'selected="selected" '; }
                   echo 'value="en">English</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'es') { echo 'selected="selected" '; }
                   echo 'value="es">Espa&#241;ol</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'fr') { echo 'selected="selected" '; }
                   echo 'value="fr">Fran&#231;ais</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'hr') { echo 'selected="selected" '; }
                   echo 'value="hr">Hrvatski Jezik</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'it') { echo 'selected="selected" '; }
                   echo 'value="it">Italiano</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'ka') { echo 'selected="selected" '; }
                   echo 'value="ka">&#4325;&#4304;&#4320;&#4311;&#4323;&#4314;&#4312;&#32;</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'nl') { echo 'selected="selected" '; }
                   echo 'value="nl">Nederlands</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'pl') { echo 'selected="selected" '; }
                   echo 'value="pl">Polski</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'pt') { echo 'selected="selected" '; }
                   echo 'value="pt">Portugu&#234;s</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'ro') { echo 'selected="selected" '; }
                   echo 'value="ro">Engleza</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'ru') { echo 'selected="selected" '; }
                   echo 'value="ru">&#1056;&#1091;&#1089;&#1089;&#1082;&#1080;&#1081;</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'sl') { echo 'selected="selected" '; }
                   echo 'value="sl">Slovensko</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'sr-Cyrl-CS') { echo 'selected="selected" '; }
                   echo 'value="sr-Cyrl-CS">&#1057;&#1088;&#1087;&#1089;&#1082;&#1080; &#1032;&#1077;&#1079;&#1080;&#1082;</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'sr-Latn-CS') { echo 'selected="selected" '; }
                   echo 'value="sr-Latn-CS">Srpski Jezik</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'sv') { echo 'selected="selected" '; }
                   echo 'value="sv">Sverige</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'tr') { echo 'selected="selected" '; }
                   echo 'value="tr">T&#252;rk&#231;e</option>
                         <option ';
                   if($_SESSION['IZ_LANG'] == 'zh-CHS') { echo 'selected="selected" '; }
                   echo 'value="zh-CHS">&#31616;&#20307;&#23383;</option>
                  </select>
                <br />                                                  
                   
                <label for="theme">',ADM_CHANGETHEME,'&#58;</label>';
                getthemes('usercust');
            echo '<br />

                <div class="buttonholder">';
//                  <input type="button" name="close" id="custpanelclose" value="',STR_CLOSE,'" class="buttondelete" onclick="showcustomiseplain(\'hide\')" />
            echo '<input type="hidden" name="fromloc" id="fromloc" value="" />
                  <button type="submit" name="setusercust" value="save" class="buttonsave">',STR_SAVE,'</button>
                </div>
              </form>
            </div><!-- end setupcal -->';
            if((($_SESSION['edit'] > 0) && (($opt_flags & OPT_CATEGORY) != 0)) || ($_SESSION['cpanel'] == 1)) {
                echo '<div id="setupcats">
                      <form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" name="cats">
                      <fieldset>
                      <legend>',ADM_ADDCAT,'</legend>
                      <label for="catname">',STR_NAME,'&#58;</label>
                      <input type="text" name="catname" id="catname" class="inline" size="30" /><br />';
                if($_SESSION['IZ_ITEMCOLORS'] == 'c') {
                  echo '<label for="catcolor">',STR_COLOUR,'&#58;</label>
                        <input type="text" name="catcolor" id="catcolor" class="inline" size="30" /><br />';
                }
                echo '<input type="submit" value="',ADM_ADDCATCAL,'" name="addcatevent" class="buttonadd" style="margin: 10px 0 0 210px" /><br />';
                if(($opt_flags & OPT_TODO) != 0) {
                    echo '<input type="submit" value="',ADM_ADDCATTODO,'" name="addcattodo" class="buttonadd" style="margin: 10px 0 0 210px" />';
                }
                echo '<input type="hidden" name="categories" value="addcat" />
                      <input type="hidden" name="store" value="store" />
                      <div class="inlineerror" id="error_addcat">&nbsp;</div>
                      </fieldset>
                      </form>';
                get_categories('customiselist');
                echo '<form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" name="cats">
                      <fieldset class="defaultcats">
                      <legend>',STR_DEFAULTCATS,'</legend>
                      <small>',STR_DEFAULTCATSDESC,'</small><br />
                      <label for="defaultevent">',STR_EVENTS,'&#58; </label>
                      <select name="defaultevent" id="defaultevent" size="1">';
                get_categories('edit',$_SESSION['defaultcategoryevents'],'event');
                echo '</select>
                      <br />';
                if(($opt_flags & OPT_TODO) != 0) {
                    echo '<label for="defaulttodo">',STR_TODO,'&#58; </label>
                          <select name="defaulttodo" id="defaulttodo" size="1">';
                    get_categories('edit',$_SESSION['defaultcategorytasks'],'task');
                    echo '</select><br />';
                }
                echo '<div class="buttonholder"><input type="submit" value="',STR_SAVE,'" name="blah" class="buttonsave" /></div>
                      </fieldset>
                      <input type="hidden" name="categories" value="savedefault" />
                      <input type="hidden" name="store" value="store" />
                   </form>
                </div> <!-- end setupcats -->';
            }
            if($_SESSION['authed'] == 1) {
              echo '<div id="setuppass">
              <form enctype="multipart/form-data" method="post" action="',$_SESSION['IZ_CALURL'],'index.php" name="cats">
                <label>',STR_OLDPASS,'&#58;</label>
                <input type="password" name="oldpass" id="oldpass" class="inline" size="30" /><br />
                
                <label>',STR_NEWPASS,'&#58;</label>
                <input type="password" name="newpass" id="newpass" class="inline" size="30" /><br />
                
                <label>',STR_CONFIRMPASS,'&#58;</label>
                <input type="password" name="confpass" id="confpass" class="inline" size="30" /><br />

                <div class="buttonholder">
                  <input type="button" name="close" id="custpanelclose" value="',STR_CLOSE,'" class="buttondelete" onclick="showcustomiseplain(\'hide\')" />
                  <input type="hidden" name="fromloc" id="fromloc" value="" />
                  <input type="hidden" name="act" value="changepass" />
                  <button type="submit" name="changepass" value="save" class="buttonsave">',STR_SAVE,'</button>
                </div>
                </form>
              </div><!-- end setuppass -->';
            }
            echo '</div> <!-- end tabcontainer -->';
}
function dumpdb($type) {
         if(strtolower($_POST['exporttype']) == 'xml') {
           include($_SESSION['IZ_CALPATH'].'includes/xml.php');
           $dbdump = exportXml();
         } else {
           izsql();
           $dbdump .= 'dat'.date("Y-m-d")."\n".'ver'.IZ_CALVERSION."\n";
           $queries = array('cat' => 'SELECT * FROM categories',
                            'com' => 'SELECT * FROM comments',
                            'eve' => 'SELECT * FROM events',
                            'grp' => 'SELECT * FROM groups',
                            'tod' => 'SELECT * FROM tasks',
                            'set' => 'SELECT * FROM settings',
                            'use' => 'SELECT * FROM users');
           if(IZ_CALMODE == 'mysql') {
             if($_SESSION['MYSQLi']) {
               global $dblink;
               foreach($queries as $prefix => $q) {
                 $res = $dblink->query($q);
                 while($row = $res->fetch_row()) {
                   $wholerow = implode('__X__',$row);
                   $dbdump .= $prefix.substr($wholerow,0,strlen($wholerow))."\n";
                 }
                 $res->close();
               }
             } else {
               foreach($queries as $prefix => $q) {
                 $res = mysql_query($q);
                 while($row = mysql_fetch_row($res)) {
                   $wholerow = implode('__X__',$row);
  //var_dump($row); echo '<br/>'.$wholerow.'<br/>'.'<br/>';
                   $dbdump .= $prefix.substr($wholerow,0,strlen($wholerow))."\n";
                 }
               }
             }
           } elseif(IZ_CALMODE == 'postgre') {
             $queries = array('cat' => 'SELECT * FROM "categories"',
                              'com' => 'SELECT * FROM "comments"',
                              'eve' => 'SELECT * FROM "events"',
                              'grp' => 'SELECT * FROM "groups"',
                              'tod' => 'SELECT * FROM "tasks"',
                              'set' => 'SELECT * FROM "settings"',
                              'use' => 'SELECT * FROM "users"');
              foreach($queries as $prefix => $q) {
               $res = pg_query($q);
               while($row = pg_fetch_row($res)) {
                 $wholerow = implode('__X__',$row);
                   $dbdump .= $prefix.substr($wholerow,0,strlen($wholerow))."\n";
               }
             }
           } elseif(IZ_CALMODE == 'msq') {
             foreach($queries as $prefix => $q) {
               $res = mssql_query($q);
               while($row = mssql_fetch_row($res)) {
                 $wholerow = implode('__X__',$row);
                   $dbdump .= $prefix.substr($wholerow,0,strlen($wholerow))."\n";
               }
             }
           }
         }
         if($type == 'file') {
           header("Pragma: public");
           header("Expires: 0");
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
           header("Cache-Control: private",false);
           header("Content-Transfer-Encoding: binary");
           if(strtolower($_POST['exporttype']) == 'xml') {
             header("Content-Type: text/xml; charset=UTF-8");
             header("Content-Disposition: attachment; filename=\"izeit-".date("Y-m-d").".xml\";" );
           } else {
             header("Content-Type: text/plain");
             header("Content-Disposition: attachment; filename=\"izeit-".date("Y-m-d").".db\";" );
           }
           header("Content-Length: ".strlen($dbdump));
           echo $dbdump;
         } elseif($type == 'disk') {
           $backupfile = @fopen($_SESSION['IZ_CALPATH'].'includes/data/backup-'.date("Y-m-d").'.db', "w");
           if($backupfile) {
             fwrite($backupfile, $dbdump);
             fclose($backupfile);
           } else {
             $error .= '<p><span style="color: #ff0000; font-weight: bold;">&#35;239&#58; '.ERR_WRITEFILE.'</span></p>';
           }
         }
}
function iz_longdate($secs) {
    global $daynames;
    global $monthnames;
    $monthnum = date('n',$secs);
    $daylong = $daynames[date('w',$secs)];
    $monthlong = $monthnames[$monthnum];
    $trans = array(
              'de' => '::', // fix for portuguese translation
              'dd' => date('d',$secs), //xd
              'd' => date('j',$secs),      //xj
              'M' => $monthnum,            //xn
              'MM' => date('m',$secs),     //xm
              'yyyy' => date('Y',$secs),   //xY
              '-S' => date('S',$secs),     //xS
              'dddd' => $daylong,          //xl
              'MMMM' => $monthlong,        //xF
              'xp' => strtolower($monthlong),
              'hh' => date('h',$secs),     //xh
              'HH' => date('H',$secs),     //xH
              'mm' => date('i',$secs),     //xi
              'tt' => date('A',$secs),      //xA
             );
    $transescape = array(
              '::' => 'de',
             );
    return strtr(strtr(IZ_LONGDATE,$trans),$transescape);
}
function iz_longdatehours($secs) {
    global $daynames;
    global $monthnames;
    $monthnum = date('n',$secs);
    $daylong = $daynames[date('w',$secs)];
    $monthlong = $monthnames[$monthnum];
    $trans = array(
              'de' => '::', // fix for portuguese translation
              'dd' => date('d',$secs), //xd
              'd' => date('j',$secs),      //xj
              'M' => $monthnum,            //xn
              'MM' => date('m',$secs),     //xm
              'yyyy' => date('Y',$secs),   //xY
              '-S' => date('S',$secs),     //xS
              'dddd' => $daylong,          //xl
              'MMMM' => $monthlong,        //xF
              'xp' => strtolower($monthlong),
              'hh' => date('h',$secs),     //xh
              'HH' => date('H',$secs),     //xH
              'mm' => date('i',$secs),     //xi
              'tt' => date('A',$secs)      //xA
             );
    $transescape = array(
              '::' => 'de',
             );
         return strtr(IZ_LONGDATEHOURS,$trans);
}
function iz_error($txt) {
   echo '<html><head><link rel="stylesheet" type="text/css" href="',$_SESSION['IZ_CALURL'],'includes/main.css" /><title>',$_SESSION['IZ_CALNAME'],' &#187; ',ERR_ERRORTEXT,'</title></head><body>
         <div id="errorbox">',$txt,'</div>
         </body></html>';
   die();
}
function mssql_escape_string($string_to_escape) {
  $replaced_string = str_replace("'","''",$string_to_escape);
  return $replaced_string;
}
/**
Calculates the column index of the specified day.
@param dayNum The actual number of the day (0=sunday - 6=saturday)
@param firstDay The starting position in the current view
*/
function getOffsetDisplayedIndex($dayNum,$firstDay='') {
    if($firstDay == '') {
      $first = $_SESSION['IZ_FIRSTDAY'];
    } else {
      $first = $firstDay;
    }
    $lower = (7 - $first) + $dayNum;
    if($lower < 7) {
        return $lower;
    } else {
        return $lower - 7;
    }
}
/**
Maps a column number to the array index in $daynames/$weekdays which holds the name of that day
Ie: Converts a column number to a day index
*/
function getLocalizedIndex($dayNum) {
    $lower = $_SESSION['IZ_FIRSTDAY'] +$dayNum;
    if($lower < 7) {
        return $lower;
    } else {
        return $lower - 7;
    }
}
function dayToWDay($day) {
  switch(strtolower($day)) {
    case 'sunday':
      return 0;
      break;
    case 'monday':
      return 1;
      break;
    case 'tuesday':
      return 2;
      break;
    case 'wednesday':
      return 3;
      break;
    case 'thursday':
      return 4;
      break;
    case 'friday':
      return 5;
      break;
    case 'saturday':
      return 6;
      break;  
  }
  return 0;
}
function WDayToDay($day) {
  switch($day) {
    case 0:
      return 'sunday';
      break;
    case 1:
      return 'monday';
      break;
    case 2:
      return 'tuesday';
      break;
    case 3:
      return 'wednesday';
      break;
    case 4:
      return 'thursday';
      break;
    case 5:
      return 'friday';
      break;
    case 6:
      return 'saturday';
      break;  
  }
  return 'sunday';
}
function parsecolor($color) {
  $parsed = $color;
  if(substr($color,0,1) != '#') {
    if(is_numeric($color) || is_numeric('0x'.$color)) {
      $parsed = '#'.$color;
    }
  }
  return $parsed;
}
function parseDotNetDate($date) {
  // returns a unix datestamp of the date.
  // Expects date in the format Y-m-d\TH:i:s (eg: 2008-03-28T15:27:00
  if(strlen($date) == 19) {
    $year = substr($date,0,4);
    $month = substr($date,5,2);
    $day = substr($date,8,2);
    $hour = substr($date,11,2);
    $minute = substr($date,14,2);
    $second = substr($date,17,2);
    return mktime($hour,$minute,$second,$month,$day,$year);
  } else {
    return mktime();
  }
}
function ismobilebrowser() {
  $_SESSION['mobilechecked'] = true;
  if(eregi('up.browser|up.link|windows ce|iemobile|mini|mmp|symbian|midp|wap|phone|pocket|mobile|pda|psp',$_SERVER['HTTP_USER_AGENT'])) {
    return true;
  }
  if(stristr($_SERVER['HTTP_ACCEPT'],'text/vnd.wap.wml')||stristr($_SERVER['HTTP_ACCEPT'],'application/vnd.wap.xhtml+xml')) {
    return true;
  }
  if(isset($_SERVER['HTTP_X_WAP_PROFILE'])||isset($_SERVER['HTTP_PROFILE'])||isset($_SERVER['X-OperaMini-Features'])||isset($_SERVER['UA-pixels'])) {
    return true;
  }
}
function iz_inlineerror($txt) {
   echo '<div id="errorbox2"><strong>',ERR_ERRORTEXT,'&#58;</strong> ',$txt,'</div>';
}
function detectlanguage() {
    $acceptlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    if(strlen(trim($acceptlang)) == 0) {
        $_SESSION['IZ_LANG'] = 'en';
    } else {
        $langs = explode(',',str_replace(' ','',$acceptlang));
        $supportedlanguages = array('cs',
                                    'de',
                                    'el',
                                    'en',
                                    'es',
                                    'fr',
                                    'hr',
                                    'it',
                                    'ka',
                                    'nl',
                                    'pl',
                                    'pt',
                                    'ro',
                                    'ru',
                                    'sl',
                                    'sv',
                                    'tr',
                                    'zh',
                                  );
        foreach($langs as $lang) {
            $abbrev = substr($lang,0,2);
            if(in_array($abbrev, $supportedlanguages)) {
              $_SESSION['IZ_LANG'] = $abbrev;
              break;
            } elseif($abbrev == 'sr') {
              $_SESSION['IZ_LANG'] = 'sr-Latn-CS';
              break;
            }
        }
    }
}
if (version_compare(phpversion(), '5.0') < 0) {
    eval('
    function clone($object) {
      $obj_clone = unserialize(serialize($object));
      return $obj_clone;
    }
    ');
}
} else {
  // Directly accessed
  header('Location: ../');
} ?>